我正在学习 Java,并且正在学习使用 java.util.Scanner
进行 I/O。具体来说,我正在学习 Scanner
方法。
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int result;
while (s.hasNextInt()) {
result += s.nextInt();
}
System.out.println("The total is " + result);
}
}
最佳答案
因为你只检查
while (s.hasNextInt())
您可以使用 try
catch
捕获程序退出时出现的异常 ( see documentation here ),以便您可以在 中显示错误消息catch
block 而不使程序关闭。
关于Java:扫描仪初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18626241/