如何在Java中使用文本文件计算数组中整数元素的总和?

huangapple 未分类评论51阅读模式
标题翻译

How do you calculate the sum of integer elements in an array using text files in Java?

问题

假设我有一个名为 "Scores.txt" 的文件,其中包含2个或更多个数组。

示例

10 20 30 40 50 //总和为150
11 21 31 41 51 //总和为155

我想要能够读取每行中的每个元素并将它们相加在一起。

另外还有跟进的问题。将整数数组正确地写入文本文件的方法是什么?如何分隔每个元素但仍然将它们放在同一行?

这是我用来编写数组的代码,但我觉得在读取元素时可能会有问题。

write() 代码

try {
    File file = new File("Scores.txt");
    BufferedWriter bWrite = new BufferedWriter(new FileWriter(file, true));
         
    int score[] = new int[5];
         
    System.out.println("输入分数: ");
    for (int i = 0; i < 5; i++) {
        score[i] = sc.nextInt();
    }
         
    for (int i = 0; i < 5; i++) {
        bWrite.write(score[i] + " ");
    }
    bWrite.flush();
    bWrite.close();
}
catch (Exception e) {
    System.out.println("错误");
}
英文翻译

Lets say I have a "Scores.txt" file containing 2 or more arrays.

Example

10 20 30 40 50 //sum is 150
11 21 31 41 51 //sum is 155

I want to be able to read each elements in a line and add them up together.

Also follow up questions. What is the correct way to write an array of integers into a text file? How do you separate each elements but still place them in one line?

This is the code I'm using to write the arrays but I have a feeling that there might be issues when reading the elements.

write() code

      try {
         File file = new File (&quot;Scores.txt&quot;);
         BufferedWriter bWrite = new BufferedWriter(new FileWriter(file, true));
         
         int score[] = new int [5];
         
         System.out.println(&quot;Enter scores: &quot;);
         for (int i = 0; i &lt; 5; i++) {
            score[i] = sc.nextInt();
         }
         
         for (int i = 0; i &lt; 5; i++) {
            bWrite.write(score[i] + &quot; &quot;);
         }
         bWrite.flush();
         bWrite.close();
    
      }
      catch (Exception e) {
         System.out.println(&quot;ERROR&quot;);
      }

huangapple
  • 本文由 发表于 2020年3月16日 19:08:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/60704836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定