[英]How would I display the position of an element in an array?
我的难题是在用户输入一个数字之后,然后检查该数字以查看它是否在数组中,如果是,我会让他们知道该数字在数组中以及该数字的位置。 我有它提示用户输入数字的位置,但是在那之后我得到了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)
将<=
更改为<
。
异常已经说明了。 您正在检查不在数组范围内的索引。 查看第二个for循环:
for(int i=0; i<=iGrades.length; ++i)
它的范围是0到30。不过,数组只能是0到29。 您必须在此处使用<代替:
for(int i=0; i < iGrades.length; i++)
由于数组是从零开始的,因此
i<=iGrades.length
将允许i
等于Grades.length
,它比数组的最后一个索引Grades.length
一个。 使用<
。
记得
数组索引从0 to length of array -1
开始0 to length of array -1
相应地更改循环
提示更改<=
到<
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.