2012-01-13 80 views
1

我的程序是将一个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(); 
} 

谢谢大家=]

+6

的Integer.parseInt(String s)将 - 将转换你的字符串到一个int – 2012-01-13 04:29:36

+2

我已经添加'家庭作业'标记,因为这清楚* *作业 – Bohemian 2012-01-13 04:33:31

+0

我应该把声明将数组中的所有字符串转换为int? – 2012-01-13 05:09:45

回答

2

请使用的Integer.parseInt(字符串值),将字符串转换为整数

+0

这个陈述应该在哪里?我应该使用for循环吗? – 2012-01-13 05:09:06

+0

@Benson:现在你有一个明确的例子,将每个值赋给一个2维的String数组('data')。将'data'声明为'int [] []',而当你给数组中的一个位置赋值的时候,使用'parseInt'。 – 2012-01-13 05:15:19

+0

对不起,还不明白。当单独扫描文件时,它是字符串,如何以及在哪里可以将它转换为int? – 2012-01-13 05:22:31