我的程序是將一個txt文件輸入到一個2d數組中用來計算和顯示一些數據。如何將String中的2d數組轉換爲int?
我輸入文件的樣子:
[學生],Exam1,Exam2,Exam3
可能,100,100,100
彼得,99,60,80
約翰,100,50,100
我是新來的java。在將txt文件輸入到2d數組後,數組將會是String數據類型,我如何將它轉換爲int類型,以便我可以計算一些統計信息,例如每個學生的平均分數,總分或班級平均分數?並應該把計算?
我的代碼:
File file = new File("test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
int width = 0, height = 0;
String line = "";
/*Find number of row and column of the file.*/
while ((line = br.readLine()) != null){
if (width == 0){
/*Find the number of row using split method(",")*/
String[] str = line.split(",");
width = str.length;
}
height++;
}
System.out.println("The text file contains:");
System.out.println("Row : " + height);
System.out.println("Column : " + width);
System.out.println("");
System.out.println("The sales figure of the company:");
/*Adding values to the 2D Array and organize data.*/
String[][] data = new String[height][width];
br = new BufferedReader(new FileReader(file));
int columnWidth = 20;
StringBuilder format;
int addition = 0;
for (int i = 0; i < height; i++){
if ((line = br.readLine()) != null)
{
String[] str = line.split(",");
for (int j = 0; j < width; j++){
data[i][j] = str[j];
format = new StringBuilder(str[j]);
for (int k = format.length(); k< columnWidth; k++){
format.append(" ");
}
System.out.print(format.toString());
}
}
System.out.println("");
}
System.out.println();
}
謝謝大家=]
的Integer.parseInt(String s)將 - 將轉換你的字符串到一個int – 2012-01-13 04:29:36
我已經添加'家庭作業'標記,因爲這清楚* *作業 – Bohemian 2012-01-13 04:33:31
我應該把聲明將數組中的所有字符串轉換爲int? – 2012-01-13 05:09:45