簡體   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