从文本文件中只读取整数并添加它们

时间:2017-09-17 23:26:29

标签: java

假设我有一个包含内容的textfile.txt:

x   y   z   sum
3   6   5
6   7   8

我想添加每一行3 + 6 + 56 + 7 + 8,并将这些总和输出到一个新的文本文件中,格式如下:

x   y   z   sum
3   6   5   14
6   7   8   21

这是我到目前为止所做的:

  public static void main(String[] args) throws IOException {

    Scanner s = new Scanner(new File("text.txt"));                
    java.io.PrintWriter output = new java.io.PrintWriter("text_output.txt");

    while (s.hasNextLine()) {
       String currentLine = s.nextLine();
       String words[] = currentLine.split(" ");


       int sum = 0;
       boolean isGood = true;
       for(String str : words) {
          try {
             sum += Integer.parseInt(str);
          }catch(NumberFormatException nfe) { };  
               continue;}

       if (isGood && sum != 0) {
           System.out.println(sum);
           output.print(sum);              
           output.close();

       }

    }
}

这将在控制台中打印所有正确的总和,但只会将第一个或最后一个总和写入新文件。如何让它将所有和值写入文件?

2 个答案:

答案 0 :(得分:1)

你快到了。设置sum以添加数字,并添加continue以跳至错误的下一行:

int sum = 0;
boolean isGood = true;
for(String str : words) {
    try {
        sum += Integer.parseInt(str);
    } catch (NumberFormatException nfe) {
        // If any of the items fails to parse, skip the entire line
        isGood = false;
        continue;
    };
}
if (isGood) {
    // If everything parsed, print the sum
    System.out.println(sum);
}

答案 1 :(得分:1)

首先,您要制作FileWriter和BufferedWriter。这将允许您写入新的文本文件。

您可以通过以下方式执行此操作:

FileWriter outputFile = new FileWriter("outputfile.txt");
BufferedWriter bw = new BufferedWriter(outputFile);

然后我会改变你的循环一点点。我会在for循环之外声明一个sum变量。 像这样:

 int sum = 0;
           for(String str : words) {

这将允许我们稍后在for循环之外使用它。然后在for循环中,我们想要将它获取的值写入文本文件。然后将其添加到我们的总和值。 像这样:

bw.write(str+ " ");
sum += Integer.parseInt(str);

完成此操作后,我们可以简单地将总和写入文件。你想把它放在for循环的一边,因为那是它已经遍历整行并将所有整数加在一起! 你可以写这样的总和:

bw.write(sum+"\n");

最后,您将要关闭BufferedWriter。你想要在循环之外做到这一点,或者在读取和写入第一行后它会关闭! 像这样关闭它:

bw.close();

然后你很高兴去!您可能需要刷新您的项目以查看它创建的新文本文件。

相关问题