Java 从文本文件中只读取整数并将其相加

Java 从文本文件中只读取整数并将其相加,java,Java,假设我有一个包含以下内容的textfile.txt: x y z sum 3 6 5 6 7 8 我想添加每一行,3+6+5和6+7+8,并以如下格式将总和输出到新的文本文件中: x y z sum 3 6 5 14 6 7 8 21 bw.write(sum+"\n"); bw.close(); 以下是我到目前为止的情况: public static void main(String[] args) throws IO

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

x   y   z   sum
3   6   5
6   7   8
我想添加每一行,
3+6+5
6+7+8
,并以如下格式将总和输出到新的文本文件中:

x   y   z   sum
3   6   5   14
6   7   8   21
bw.write(sum+"\n");
bw.close();
以下是我到目前为止的情况:

  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();

       }

    }
}

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

你就快到了。进行一次
求和
以将数字相加,然后添加
继续
以在出现错误时跳到下一行:

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);
}

因此,首先您需要创建FileWriter和BufferedWriter。这将允许您写入新的文本文件

您可以通过以下方式完成此操作:

FileWriter outputFile = new FileWriter("outputfile.txt");
BufferedWriter bw = new BufferedWriter(outputFile);
然后我会改变你的循环一点。我会在for循环之外声明一个sum变量。 像这样:

 int sum = 0;
           for(String str : words) {
bw.write(str+ " ");
sum += Integer.parseInt(str);
这将允许我们稍后在for循环之外使用它。然后在for循环中,我们要将它得到的值写入文本文件。然后把它加到我们的总值中。 像这样:

 int sum = 0;
           for(String str : words) {
bw.write(str+ " ");
sum += Integer.parseInt(str);
完成后,我们可以简单地将总和写入文件。您希望将其放在for循环的外侧,因为此时它已遍历整行并将所有整数相加! 你可以这样写总数:

x   y   z   sum
3   6   5   14
6   7   8   21
bw.write(sum+"\n");
bw.close();
最后,您需要关闭BufferedWriter。您需要在while循环之外执行此操作,否则它将在读写第一行后关闭! 像这样关闭它:

x   y   z   sum
3   6   5   14
6   7   8   21
bw.write(sum+"\n");
bw.close();

然后你就可以走了!您可能需要刷新您的项目以查看它创建的新文本文件。

那么您的问题到底是什么?只是难以获得正确数字的总和。