【问题标题】:How to use Scanner to read only one line at a time with integers?如何使用扫描仪一次只读取一行整数?
【发布时间】:2019-08-11 10:18:58
【问题描述】:

如果我有一个包含数字列表的 .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

【问题讨论】:

  • 目前(在程序中)您正在尝试计算行的总和,scuner 位于数据流的末尾。同时计算行总和和总和可能是一个更好的主意,例如在同一个循环中。

标签: java file java.util.scanner java-io


【解决方案1】:

问题:

您的问题是您使用相同的Scanner 实例两次读取文件,这是导致问题的原因,因为它在第一次while 调用中已经到达文件末尾,所以当您回忆@ 987654323@ 它将是false,因此您不会输入第二个while

解决方案:

您需要在第二次 while 调用之前重新初始化 input 扫描器:

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() 调用以获得所需的行为。

【讨论】:

  • 不敢相信我没有考虑到这一点,但是第二次仍然需要每个数字,而不仅仅是数字行。无论我尝试什么,我都无法单独添加每一行。
  • @IanHank 这就是为什么我说你需要注意input.next() 调用,它读取所有行但作为String,然后你可以得到所有的数字。
【解决方案2】:

您的第二个循环将永远无法工作,因为在第一个循环之后您处于 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);

我的打印方式与您的略有不同,但这很容易解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多