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

时间:2014-08-20 04:19:53

标签: java file io while-loop

我刚刚完成了一个提示用户输入文字File输入IO的应用程序,但我有一些要澄清的最后部分,While loop我实际设法将其引用到关于谷歌的教程。在这个循环中,有一个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 没有更多令牌可供阅读,它就会离开while loop不是吗?为什么它仍然会进入下一个标记?我糊涂了。请指教谢谢! ;)

2 个答案:

答案 0 :(得分:2)

Why does it has still go onto the next token?

这是因为当执行nextInt()时,它将消耗文件中的int number但在其中,它具有需要消耗的newLine字符,即next时{}执行1}}以在newLine之后使用int number

示例文件内容:

1

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

答案 1 :(得分:1)

In this loop, there is a if-else statement and for the else part I don't understand 
why is it necessary.

如果找到int值,则fileInput.hasNexInt()方法返回true,而不是执行添加操作。如果下一个值不是int类型,那么part将执行fileInput.next()将返回下一个值(指针将指向该值之后),不执行任何操作意味着转义下一个值(可以是除int-type之外的任何类型)。如果条件将检查int。

相关问题