Java 扫描仪在循环结束后读取
Scanner.hasNext读取是否有令牌,当没有令牌时,它应该结束循环,但获取错误未找到此类元素异常,但当我切换第1行和第2行时,我工作正常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
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;
}