【问题标题】:Java - Adding up integers from a fileJava - 将文件中的整数相加
【发布时间】: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


【解决方案1】:

当您在第一个打印语句中调用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

【讨论】:

  • 向他们展示他们现在需要做什么来解决问题
  • 谢谢!那么将它们加在一起的最佳方法是什么?
  • 拿出你的打印声明。
【解决方案2】:

在你的 while 循环中添加一个临时变量:

            while (scanner.hasNextInt()) {
                int cur = scanner.nextInt();
                System.out.println(cur);
                total += cur;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多