繁体   English   中英

如何使用扫描仪一次仅读取整数行?

[英]How to use Scanner to read only one line at a time with integers?

如果我有一个带有数字列表的.txt文件。 它应该返回每一行中所有数字的总和以及文件中每个数字的总和。 然后在控制台中打印所有这些。 可以说txt文件是:

50  3   21  10  9   9   54  47  24  74
22  63  63  28  36  47  60  3   45  83
20  37  11  41  47  89  9   98  40  94
48  77  93  68  8   19  81  67  80  64
41  73  24  29  99  6   41  23  23  44
43  41  29  11  43  94  62  27  81  71
83  14  97  67  21  68  77  25  21  24
31  8   54  14  49  96  33  18  14  80
54  55  53  38  62  53  62  10  42  29
17  89  92  87  15  42  50  85  68  43

这是我的代码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Summer {
    public static void main(String args[]) throws IOException {

        File text = new File("src/nums.txt");

        if (!text.exists()) {
          text.createNewFile();
        }

        int sum = 0;
        Scanner input = new Scanner(text);
        while (input.hasNextInt()) {
            sum = sum + input.nextInt();

        }

        System.out.printf("Sum of all numbers: %d", sum);


        int lineSum = 0;
        int lineNum = 1;

        while (input.hasNext()) {
            if (input.hasNextInt()) {
                lineSum = lineSum + input.nextInt();
            } else {
                input.next();
                lineNum++;
            }
        }

        System.out.printf("%nSum of line %d: %d", lineNum, lineSum);
    }
}

哪个输出:

Sum of all numbers: 4687
Sum of line 1: 0

您的第二个循环将永远无法进行,因为在第一个循环之后您处于EOF(文件结束)位置,并且扫描程序对象不会从头开始。

最好的方法是使用2个Scanner对象,一个从文件中读取一行,另一个从该行中读取值。 使用此解决方案,您可以一次计算每行总计和文件总计。

int total = 0;
Scanner input = new Scanner(text);
while (input.hasNextLine()) {
    Scanner lineScanner = new Scanner(input.nextLine());
    int lineSum = 0;
    while (lineScanner.hasNextInt()) {
        lineSum += lineScanner.nextInt();
    }
    System.out.println(Sum of line is: " + lineSum);
    total += lineSum;
}
System.out.println("File sum is: " + total);

我的打印与您的打印有些不同,但是很容易修复。

问题:

这里的问题是您使用同一Scanner实例两次读取文件,这引起了问题,因为它在第一次while调用中已经到达文件的末尾,因此,当您调用input.hasNext() ,它将false因而你不会进入第二个while

解:

您需要在第二个while调用之前重新初始化input Scanner:

int lineSum = 0;
int lineNum = 1;

//Re initialize the scanner instance here
input = new Scanner(text);
while (input.hasNext()) {
    //Do the calculations
}

注意:

您还需要在计算中注意input.nextInt()input.next()调用以获得所需的行为。

暂无
暂无

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

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