繁体   English   中英

如何从Java文件中读取一行中的每个整数?

[英]How to read every Integers in a line from a file in Java?

我的文件有n行整数。 我想在每行中添加每个int并打印它们(因此我应该在末尾打印3个int,每行一个一行)。

我试过了,但是它将在第一个循环中读取并添加所有Integer。

scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
    while (scan.hasNextLine()) {
         sum += scan.nextInt();
    }
    System.out.println(sum);
    sum = 0;
}

此行为是由错误使用循环和扫描引起的。 正确的解决方案之一还结合了Java 8 lambda,并假定文件中整数的定界符为space(“”):

    Path path = Paths.get("your path");
    try{
        Files.lines(path)
                .map( line -> line.split(" "))
                .mapToInt( numbers -> Arrays.stream(numbers)
                   .reduce(0 , (sum, num) -> sum + Integer.parseInt(num), (first, second) -> first + second ))
                .forEachOrdered(System.out::println);

    } catch (IOException e){
        e.printStackTrace();
    }

我想我也可以做...

read = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = read.nextInt(), j;
int sum = 0;
for (int i = 0; i < n; i++) 
{
    String[] str;
    int t = read.nextInt();
    // First str will be ""(it reads the end of each line) 
    str = read.nextLine().split(" ");
    // Then it can read what we want
    str = read.nextLine().split(" ");
    for (j = 0; j < str.length; j++) 
    {
        sum += Integer.parseInt(str[j]);
    }
    System.out.println(sum);
    sum = 0;                
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM