我在使用Java代码时遇到麻烦。我应该在循环中输入“成绩”(我的退出条件是-1),然后将其放入频率表中,问题是我收到此错误:
java.lang.ArrayIndexOutOfBoundsException: -1
at MakeUp.main(MakeUp.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
这是我的代码:
class MakeUp
{
public static void main (String[] args)
{
int grade[];
int freq[]=new int [50];
grade= new int [50];
int count=0,mark;
System.out.println("Enter the grades of the class");
System.out.println("Just enter -1 to end the input");
do
{
System.out.println("Grade " +(count+1)+":");
mark=In.getInt();
if (mark>=0)
{
grade[count]=mark;
count=count+1;
}
}
while(mark!=-1);
for (int i=0; i < grade.length;i++)
{
grade[i]=mark;
}
if (mark==-1)
{
for (int i=0; i<grade.length;i++)
{
++freq[grade[i]];
}
System.out.println("Results");
for (int i=0; i<grade.length;i++)
{
System.out.println("Grade " +(i+1) + " = " +grade[i]);
}
System.out.println("Face\tFrequency\"");
System.out.println("=====================");
for (int i = 0; i<freq.length; i++)
{
System.out.println((i+1)+"\t"+freq[i]);
}
}
}
}
我不确定是什么问题,并且我尝试更改有问题但无济于事的第35行。任何帮助都感激不尽。谢谢
最佳答案
以下循环用grade
值填充您的-1
数组(因为mark
= -1,这是之前执行的do-while循环的退出条件):
for (int i = 0; i < grade.length; i++) {
grade[i] = mark;
}
在这里,任何
grade[i]
= -1,因此您尝试从freqs
数组访问索引-1:++freq[grade[i]];