2013-04-24 91 views
0

好的,所以我有這段代碼把我的.csv文件中有這些值。如何從我的Java文件中獲取值並計算它們?

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

} 
} 
} 
+0

請不要使用DataInputStream來讀取文本。這是多餘的和令人困惑的。請將其從您的示例中刪除,因爲此錯誤代碼被複制了很多。 – 2013-04-28 18:09:44

回答

0

我建議String#split讀一行的值到一個數組:

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

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

在索引0的值是名稱,其他數組字段包含數字作爲字符串和你可以使用Integer#parseInt將它們轉換爲整數值。

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