Java - 将文件中的整数相加

标签 java exception integer java.util.scanner

我在添加文件中的整数时遇到问题。该代码可以很好地显示整数,但是一旦我添加“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/

相关文章:

java - 尝试从 Array.asList 返回的列表中删除时出现 UnsupportedOperationException

Java 9、Jigsaw 和自动模块

java - Webdriver 支持 selenium java - 如何验证页面文本中的 %

Java导入库源码ExceptionInInitializerError异常

objective-c - Objective-C 中的整数数组

python - TypeError : tuple indices must be integers

在 C 中将字符串打印为整数的困惑

java - 如何重新使用此表

java - Oracle JDBC 的 CallableStatement getParameterMetaData().getParameterType() 的替代方案是什么?

c# - 为私有(private)方法断言异常