我的困境是用户输入一个数字后,然后检查该数字是否在数组中,如果是,我会让他们知道该数字以及该数字的位置在数组中。我将它放在提示用户输入数字的位置,但之后我收到 ArrayIndexOutOfBoundsException 错误。
这是我到目前为止所拥有的:
int [] iGrades = new int [30];
System.out.print ("Enter the grades, when you're done input (-1) ");
for (int i=0; i<iGrades.length;i++)
{
iGrades [i]= kb.nextInt();
if (iGrades [i]< 0)
{
break;
}
}
System.out.print ("\nEnter a grade to check if it's in the array");
iVal = kb.nextInt();
for(int i=0; i<=iGrades.length; ++i)
{
if(iVal == (iGrades[i]))
{
found = true;
for(int j=0; j<=iGrades.length; ++j)
{
iGrades[j]=j+1;
}
break;
}
}
if (found == true)
{
System.out.println(iVal + " is in the array at position ");
}
else
{
System.out.println(iVal + " is NOT in the array.");
}
}
任何帮助都会很棒。
最佳答案
问题出在你的第二个 for
环形。这个
for(int i=0; i<=iGrades.length; ++i)
更改 <=
至<
。
关于java - 如何显示数组中元素的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27020060/