繁体   English   中英

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

[英]Reading only integers from text file and adding them

可以说我有一个包含内容的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();

       }

    }
}

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

你快到了 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);
}

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

您可以通过以下方式做到这一点:

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

然后,我会稍微改变一下for for loop。 我会在for循环之外声明一个sum变量。 像这样:

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

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

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

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

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

最后,您将要关闭BufferedWriter。 您将要在while循环之外进行此操作,否则它将在读取和写入第一行后关闭! 像这样关闭它:

bw.close();

然后您就可以出发了! 您可能需要刷新项目才能看到它创建的新文本文件。

暂无
暂无

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

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