【发布时间】:2012-01-13 04:24:16
【问题描述】:
我的程序是将一个 txt 文件输入到一个二维数组中,用于计算和呈现一些数据。
我的输入文件如下所示:
[学生],考试1,考试2,考试3
五月, 100, 100, 100
彼得, 99, 60, 80
约翰, 100, 50, 100
我是 Java 新手。将 txt 文件输入二维数组后,数组将是 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) - 这会将您的 String 转换为 int
-
我添加了
homework标签,因为这显然是功课 -
将数组中的所有String转换为int的语句应该放在哪里?
-
这就是发明
fizzbuzz的原因!
标签: java string multidimensional-array