0

好的,所以我有这段代码来获取我的 .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());

}
}
}
4

2 回答 2

1

这是可以帮助您开始的代码片段。

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]);
}
于 2013-04-24T15:05:11.983 回答
0

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

String[] values = strLine(",");

// debug
for (String value:values) {
   System.out.println(value);
}

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

于 2013-04-24T15:03:59.030 回答