2012-01-13 54 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

相關問題