java - 循环结束后扫描仪读取

标签 java input java.util.scanner

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/

相关文章:

java - 在静态 try-catch 中分配静态最终变量

java - 带路径压缩的加权快速联合

java - Spring引导JPA中的“ConverterNotFoundException”

Java 扫描仪输入,测试按钮是否按下

HTML5 : Set input pattern to fixed value

java - Scanner、nextInt 和 InputMismatchException

java - 当我调用 Jenkins json api 时,如何判断构建是否正在进行?

Java:如何在控制台的一行中有两个或多个输入

扫描仪的 Java 问题

twitter-bootstrap - Bootstrap 表单中的提交按钮对输入键没有反应