Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 扫描仪在循环结束后读取_Java_Input_Java.util.scanner - Fatal编程技术网

Java 扫描仪在循环结束后读取

Java 扫描仪在循环结束后读取,java,input,java.util.scanner,Java,Input,Java.util.scanner,Scanner.hasNext读取是否有令牌,当没有令牌时,它应该结束循环,但获取错误未找到此类元素异常,但当我切换第1行和第2行时,我工作正常 public class ScannerDemo { public static void main(String[] args) { String s = "Hello World! 3 + 3.0 = 6.0 true "; Long l = 13964599874l; s = s

Scanner.hasNext读取是否有令牌,当没有令牌时,它应该结束循环,但获取错误未找到此类元素异常,但当我切换第1行和第2行时,我工作正常

    public class ScannerDemo {

    public static void main(String[] args) {

        String s = "Hello World! 3 + 3.0 = 6.0 true ";
        Long l = 13964599874l;
        s = s + l;

        // create a new scanner with the specified String Object
        Scanner scanner = new Scanner(s);

        // find the next long token and print it
        // loop for the whole scanner
        while (scanner.hasNext()) {

            // if the next is a long, print found and the long
            // LINE 1
            if (scanner.hasNextLong()) {
                System.out.println("Found :" + scanner.nextLong());
            }
            // if no long is found, print "Not Found:" and the token
            // LINE 2
            System.out.println("Not Found :" + scanner.next());

        }
    }
}
错误

Not Found :Hello
Not Found :World!
Found :3
Not Found :+
Not Found :3.0
Not Found :=
Not Found :6.0
Not Found :true
Found :13964599874
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at ScannerDemo.main(ScannerDemo.java:23)

使用类似这样的if-else

if (scanner.hasNextLong()) {
       System.out.println("Found :" + scanner.nextLong());
}else{

      System.out.println("Not Found :" + scanner.next());
}
问题是,如果在接下来的2次通话中有下一次通话,但最后没有更多的元素

在您的代码字符串中是
helloworld!3+3.0=6.0真13964599874

现在想想你调用
nextLong
时,它发现
13964599874
,但是当你再次调用
next()
时,你会得到错误
NoTouchElementException
为什么?因为在
13964599874

之后什么都不是,这是因为您没有停止循环。读取
后,它将继续:
System.out.println(“未找到:+scanner.next())

通过在
System.out.println(“找到:+scanner.nextLong())之后添加
continue
来修复它


是的,我犯了一个愚蠢的错误,我不会删除这个问题,因为另一个人会做这个愚蠢的事情
        if (scanner.hasNextLong()) {
            System.out.println("Found :" + scanner.nextLong());
            continue;
        }