java - 为什么我的 while 循环需要这行代码才能运行?

标签 java file io while-loop

我刚刚完成了一个应用程序,提示用户输入文本File输入IO,但我有一些需要澄清的最后部分,While循环 我实际上设法将其引用谷歌上的教程。在这个循环中,有一个 if-else 语句,对于 else 部分,我不明白为什么有必要。

这是我的代码:

import java.io.*;
import java.util.*;

class FileReadingExercise2 {

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        Scanner fileInput = null;

        do {
            try {
                System.out.println("Please enter the name of a file or type QUIT to finish");
                String a = userInput.nextLine();

                if (a.equals("QUIT")) { // if user inputs QUIT then stop application
                    System.exit(0);
                }

                fileInput = new Scanner(new File(a)); // the file contains text and integers
            } catch (FileNotFoundException e) {
                System.out.println("Error - File not found");
            }
        } while (fileInput == null);

        int sum = 0;

        while (fileInput.hasNext()) // continues loop as long as there is a next token
        {
            if (fileInput.hasNextInt()) // if there is an int on the next token
            {
                sum += fileInput.nextInt(); // then adds the int to the sum
            } else {
                fileInput.next(); // else go to the next token
            }
        }
        System.out.println(sum);
        fileInput.close();
    }
}

如您所见,只要fileInput Scanner 有下一个要查找的标记,即可操作 if else 语句。如果 fileInput 有下一个 Int,则将其添加到 sum 变量中。所以我认为这就足够了。一旦 fileInput 没有更多的 token 可供读取,它就会退出 while 循环,不是吗?为什么它仍然进入下一个 token ?我很困惑。请指教谢谢! ;)

最佳答案

Why does it has still go onto the next token?

这是因为当执行 nextInt() 时,它将消耗文件中的 int number 但在其中,它有一个 newLine需要消耗的字符,即执行 next 时消耗 int number 之后的 newLine

示例文件内容:

1

实际上有 1 字符和换行符 \n 字符

关于java - 为什么我的 while 循环需要这行代码才能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25396662/

相关文章:

io - 过滤掉断管错误

swift - 如何通过在 webView 中单击按钮来呈现 ViewController? swift/Xcode

c# - 缓存是否需要同步?

java - 许多版本的 JDK : How do I specify which one is used?

python - 在 django 中哪里可以找到上传图片的管理代码?

file - 测试来自 `ls/dev` 的字符串并只回显 block 文件

java - SSLSocketImpl.startHandshake() 在恢复缓存 session 时抛出 SSLHanshakeException/EOFException

java - Java Math.pow 的错误结果

java - getClass().getResourceAsStream ("/folder") 返回 null

java - 具有最低和最高价格的产品(数据从文本文件中读取)