我的程序是将一个txt文件输入到二维数组中,用于计算和显示一些数据。
我的输入文件如下:
[学生],考试1,考试2,考试3
可以,100,100,100
彼得,99,60,80john,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();
}
谢谢大家=]
答案 0 :(得分:2)
请使用Integer.parseInt(String value)将字符串转换为整数