从文件中添加整数?

时间:2018-12-05 15:25:26

标签: java file

我试图从文件中读取整数,然后将它们添加到总计中,然后dsplay总计。我有这段代码,但似乎卡在while块中,不确定为什么吗?任何帮助将不胜感激。

import java.io.*;
import java.util.Scanner;

public class HandlingExceptions {

int num;
int total = 0;

public HandlingExceptions () {
}

public void read () {
    FileReader fr;
    try {
        fr = new FileReader("integers.txt");
        BufferedReader br = new BufferedReader(fr);
        Scanner scan = new Scanner(br);
        try {
            num = br.read();
            while (scan.hasNextInt()) {
                total = total + num;
            }
            System.out.println("THE TOTAL OF THE VALUES IS: " + total);
        } catch (IOException e) {
            e.printStackTrace();
        }
        scan.close();
    } catch (FileNotFoundException e) {
        System.err.println("<<FILE NOT FOUND>>");
        e.printStackTrace();
    }
}

    public static void main (String args[]) {
        HandlingExceptions method = new HandlingExceptions();
        method.read();
    }
}

1 个答案:

答案 0 :(得分:0)

这取决于您的integers.txt文件的格式,但是数字是否用空格分隔:

try (BufferedReader reader = Files.newBufferedReader(Path.of("integers.txt"))) {
    int total = reader.lines()
            .flatMap(l -> Arrays.stream(l.split("\\s+")))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .sum();
    System.out.println(total);
}

请注意,将正整数更快或更晚地加在一起将产生integer overflow