2014-02-11 96 views
0

這裏我們繼續...當我嘗試一個3學生和3個類的示例時,輸入可以正常工作,直到最後一個類拋出異常。這是沒有道理的,因爲長度應該適合for循環...任何人都可以找到這裏有什麼問題嗎?ArrayIndexOutOfBounds 2維數組異常

import java.io.*; 

public class Application 
{ 
public static void main() 
{ 
    int studentNum = 0; 
    int courseNum = 0; 

    System.out.println("\f------GRADE CALCULATOR------\n"); 
    try 
    { 
     BufferedReader buffin = new BufferedReader(new InputStreamReader (System.in)); 
     System.out.print("Enter number of students: "); 
     System.out.flush(); 
     studentNum = Integer.parseInt(buffin.readLine()); 
     System.out.print("Enter number of courses to compute grades for: "); 
     System.out.flush(); 
     courseNum = Integer.parseInt(buffin.readLine()); 

     int grades[][] = {new int[studentNum], new int[courseNum]}; 
     System.out.println("\nEntering grades for " + studentNum + " students for " + courseNum + " classes.\n"); 
     System.out.println(grades.length); 
     for (int i = 0; i < studentNum; i++) 
     { 
      System.out.println("Entering grades for student #" + (i+1) + "..."); 
      for (int k = 0; k < courseNum; k++) 
      { 
       System.out.print("Enter grade recieved in course #" + (k+1) + ": "); 
       System.out.flush(); 
       char letterGrade = (buffin.readLine()).charAt(0); 
       if (letterGrade == 'A' || letterGrade == 'a') 
        grades[i][k] = 4; 
       else if (letterGrade == 'B' || letterGrade == 'b') 
        grades[i][k] = 3; 
       else if (letterGrade == 'C' || letterGrade == 'c') 
        grades[i][k] = 2; 
       else if (letterGrade == 'D' || letterGrade == 'd') 
        grades[i][k] = 1; 
       else if (letterGrade == 'F' || letterGrade == 'f') 
        grades[i][k] = 0; 
       else 
       { 
        System.out.println("\nInvalid entry! Acceptable inputs are A, B, C, D, or F.\n"); 
        k--; 
       } 
      } 
     } 
    } 
    catch (IOException e) 
    { 
    } 
} 
} 
+0

錯誤發生在哪裏? – Antimony

+0

k--; <<<<<當k == 0 – willll

+0

@willl時,for循環會在循環結束時添加一個,所以當k == 0時,k--將等於-1,for循環會添加一個,將該值返回到0。 –

回答

2

這行代碼是問題:

int grades[][] = {new int[studentNum], new int[courseNum]}; 

要初始化有兩個元素的數組:studentNum元素的數組,並courseNum元素的數組。

什麼,你應該做的是這樣的:

int grades[][] = new int[studentNum][courseNum]; 
1

的問題是,你正在創建等級爲長度的兩個陣列,這是數組的元素。您可能打算創建一個像這樣的多維數組。

int[][] grades = new int[studentNum][courseNum]; 

這將創建一個studentNum元素數組,每個元素都被初始化爲一個courseNum類型的數組。

0

int grades[][] = {new int[studentNum], new int[courseNum]};

什麼正在創建這裏是具有2

  • 長度的陣列。在索引0你必須在索引1 new int[studentNum]
  • 你有new int[courseNum]

所以你有兩個不同長度的數組。