我刚刚完成了一个应用程序,提示用户输入文本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/