Scanner.hasNext 读取是否有 token ,当没有 token 时,它应该结束循环,但是出现错误,没有找到这样的元素异常,但是当我切换第 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)
最佳答案
那是因为你没有停止循环。读取Long
后,它将继续:
System.out.println("未找到:"+ Scanner.next());
通过在 System.out.println("Found :"+ Scanner.nextLong()); 之后添加
continue
来修复此问题
if (scanner.hasNextLong()) {
System.out.println("Found :" + scanner.nextLong());
continue;
}
关于java - 循环结束后扫描仪读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32625850/