我在添加文件中的整数时遇到问题。该代码可以很好地显示整数,但是一旦我添加“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);
}
}
最佳答案
当您在第一个打印语句中调用scanner.nextInt()时,您将索引到下一个数字。因此,当您再次调用它时,您只需跳过一个值即可。
换句话说,如果你有 10、20、30
System.out.print(scanner.nextInt())// performs nextInt() which prints 10 and moves to 20
total += scanner.nextInt(); //will use the value of 20 instead of 10 because you are currently at 20 and moves the pointer to 30
关于Java - 将文件中的整数相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47557602/