有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异常Java从文件中添加整数

我在添加文件中的整数时遇到问题。代码在显示整数时运行良好,但只要我添加“total+=scanner.nextInt();”它每隔一个整数跳过一次(例如,如果文件包含-10、20、30、40、50,它将只显示10、30、50。并且显示总计60(?),给了我一个无趣的惊喜。我做错了什么

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);
        }

}

共 (2) 个答案

  1. # 1 楼答案

    当你呼叫扫描器时。nextInt()在第一个print语句中,索引到下一个数字。因此,当您再次调用它时,只需跳过一个值

    换句话说,如果你有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. # 2 楼答案

    在while循环中添加临时变量:

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