从文件中添加数字

时间:2015-12-03 20:49:54

标签: java java.util.scanner

我试图从文件中读取整数,然后显示它们并将它们一起添加,然后显示总数。但是,我的代码无效,sum += scan.nextInt();导致错误。有人可以帮助我吗?

import java.util.Scanner;
import java.io.File;
public class HandlingExceptions {

public static void main(String[] args) throws Exception {
    int sum = 0;

    File numbersFile = new File("numbers.txt");

    Scanner scan = new Scanner(numbersFile);

    while(scan.hasNextInt()){
        System.out.println(scan.nextInt());
        sum += scan.nextInt();
    }

    System.out.println(sum);

    scan.close();
    }

}

控制台在运行时显示以下内容:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at HandlingExceptions.main(HandlingExceptions.java:20)

1 个答案:

答案 0 :(得分:2)

此代码存在问题,因为您要使用一个数字进行打印,而另一个要添加。另一个问题是,如果你在扫描仪中有奇数,那么你会遇到NoSuchElementException

while(scan.hasNextInt()){
    System.out.println(scan.nextInt());
    sum += scan.nextInt();
}

将其更改为:

while(scan.hasNextInt()){
    int tempInt = scan.nextInt();
    System.out.println(tempInt);
    sum += tempInt;
}