這裏我們繼續...當我嘗試一個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)
{
}
}
}
錯誤發生在哪裏? – Antimony
k--; <<<<<當k == 0 – willll
@willl時,for循環會在循環結束時添加一個,所以當k == 0時,k--將等於-1,for循環會添加一個,將該值返回到0。 –