【问题标题】:How do I get values out of my file in Java and calculate them?如何从 Java 文件中获取值并计算它们?
【发布时间】:2013-04-18 04:53:45
【问题描述】:

好的,所以我有这段代码来获取包含这些值的 .csv 文件。

Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78

我想取名字,然后是相应的成绩,然后计算他们的平均值。我坚持的部分实际上是在文件中检索这些值,以便我可以实际使用它们。我将使用什么来读取字符串以便将整数提取出来?

import java.io.*;
import java.util.*;

public class Grades {
public static void main(String args[]) throws IOException
{
try{
// Open the file that is the first 
// command line parameter
FileInputStream fstream = new FileInputStream("filescores.csv");


BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());

}
}
}

【问题讨论】:

  • 请不要使用 DataInputStream 读取文本。这是多余的和令人困惑的。请从您的示例中删除它,因为此错误代码被大量复制。

标签: java string file csv io


【解决方案1】:

这里是帮助您开始的代码 sn-p。

String[] parts = strLine.split(",");
String name = parts[0];
int[] numbers = new int[parts.length - 1];
for (int i = 0; i < parts.length; i++) {
    numbers[i] = Integer.parseInt(parts[i+1]);
}

【讨论】:

    【解决方案2】:

    我建议String#split 将一行的值读入数组:

    String[] values = strLine(",");
    
    // debug
    for (String value:values) {
       System.out.println(value);
    }
    

    索引 0 处的值是名称,其他数组字段包含数字作为字符串,您可以使用 Integer#parseInt 将它们转换为整数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 2018-07-06
      • 2015-05-27
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多