gpt4 book ai didi

java - 二维数组的 ArrayIndexOutOfBounds 异常

转载 作者:行者123 更新时间:2023-12-01 23:12:21 26 4
gpt4 key购买 nike

开始吧...当我尝试一个包含 3 个学生和 3 个类(class)的示例时,输入工作正常,直到最后一个类(class),它抛出异常。这没有意义,因为长度应该适合 for 循环...有人能发现这里出了什么问题吗?

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)
{
}
}
}

最佳答案

这行代码就是问题所在:

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

您正在初始化一个包含两个元素的数组:studentNum 元素数组和 courseNum 元素数组。

你应该做的是:

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

关于java - 二维数组的 ArrayIndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com