2015-11-30 73 views
0

我構建(很差)一個二維數組來保存學生姓名和成績。它確實提示我給學生的名字等於我想要的數量,但它不適用於成績。另外它說,我有一個索引超出界限,我不知道如何發生。我如何使用二維數組

private void studentArray() { 
      int rows = 0; 
      int col = 0; 

      Scanner input = new Scanner(System.in); 

      System.out.println("How many students do you have?"); 
      rows = input.nextInt(); 

      System.out.println("How many tests would you like to record?"); 
      col = input.nextInt(); 

      String [][] schoolArray = new String[rows][col]; 

      for (int row = 0; row < rows; row++){ 
      System.out.println("Please enter student name."); 
      schoolArray[row][0] = input.next(); 
       for(int cols = 1; cols < col; cols++){ 
       System.out.println("Please enter grades."); 
       schoolArray[cols][0] = input.next(); 
       }//end of col for loop 
     }//end of row for loop 
      printSchool (schoolArray, rows, col); 


     }//end of studentArray 

     private void printSchool(String[][]schoolArray, int rows, int col){ 
      for (int row = 0; row < schoolArray.length; row ++) { 
       System.out.print(schoolArray[rows][col + 1] + "\t"); 
      } 
     } 
+1

更改'for(int cols = 1; cols

+0

我們應該有等級數量決定列的數量,現在它要求我正確的時間量,但是當它應該顯示它給出一個索引超出範圍 –

+0

@ donovanlinder多數民衆贊成那是因爲你正在使用'行'和「col」變量。哪些持有多少行和多少列的價值 – 3kings

回答

0

我想你已經錯school[cols][0]寫了這應該是school[row][cols]山坳裏面for循環

0

首先使用 -

schoolArray[row][cols] = input.next(); 

,而不是

schoolArray[cols][0] = input.next(); 

,改變printSchool方法-

private void printSchool(String[][]schoolArray, int rows, int col){ 
       for (int row = 0; row < rows; row ++) { 
         System.out.print("\n"); 
         for(int cols= 0; cols < col ;cols++){ 

        System.out.print(schoolArray[row][cols] + "\t"); 
        } 
       } 
      }