【发布时间】:2018-05-13 10:42:58
【问题描述】:
我在添加文件中的整数时遇到问题。代码可以很好地显示整数,但只要我添加“total +=scanner.nextInt();”它跳过所有其他整数(例如,如果文件包含 - 10、20、30、40、50,它只会显示 10、30、50。并显示总共 60(?)),并给我一个 NoSuchElementException。我在这里做错了什么?
import java.io.File;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class AddingInts {
public static void main(String[] args) {
File myFile = new File("ints.txt");
Scanner scanner = null;
int total = 0;
System.out.println("Integers:");
try {
scanner = new Scanner(myFile);
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
//total += scanner.nextInt();
}
}
catch (IOException ex) {
System.err.println("File not found.");
}
catch (InputMismatchException ex) {
System.out.println("Invalid data type.");
}
catch (NoSuchElementException ex) {
System.out.println("No element");
}
finally {
if (scanner != null) {
scanner.close();
}
}
System.out.println("Total = " + total);
}
}
【问题讨论】:
-
因为您要打印第一个 int 然后分配下一个 int 等
标签: java exception integer java.util.scanner