try {
Scanner s = new Scanner(new File("script.txt"));
int i = 0;
if (s.hasNext()){
i = s.nextInt();
}
System.out.println(i);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
现在一切都是正确的,谢谢你的帮助。我发现了自己的错误! :)
答案 0 :(得分:1)
因为你在打印i之前就给了我5个。
答案 1 :(得分:0)
i = 5; // <--- You are assigning the value 5 here.
System.out.println(i); // <--- and printing it here.
答案 2 :(得分:0)
如果您希望在控制台上只打印一个数字,那是错误的:
try {
Scanner s = new Scanner(new File("script.txt"));
System.out.println(s.nextLine()); //<-- HERE YOU PRINT FIRST!
int i = 0;
if (s.hasNext()){
i = s.nextInt();
}
i = 5;
System.out.println(i); //<-- HERE YOU PRINT THE SECOND NUMBER!
} catch (FileNotFoundException e) {
e.printStackTrace();
}
所以你打电话两次System.out.println()
通常按照方法说明打印两行。