[英]How would I display the position of an element in an array?
My dilemma is after the user inputs a number, that number is then checked to see if it's in the array, if it is i'll let them know that is in the array along with the position of that said number. 我的难题是在用户输入一个数字之后,然后检查该数字以查看它是否在数组中,如果是,我会让他们知道该数字在数组中以及该数字的位置。 I have it to where it prompts user for the number, but after that i get the ArrayIndexOutOfBoundsException error.
我有它提示用户输入数字的位置,但是在那之后我得到了ArrayIndexOutOfBoundsException错误。
Here's what I have so far: 这是我到目前为止的内容:
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.");
}
}
Any assistance would be great. 任何帮助都会很棒。
The problem is in your second for
loop. 问题出在第二个
for
循环中。 This 这个
for(int i=0; i<=iGrades.length; ++i)
Change the <=
to <
. 将
<=
更改为<
。
The exception says it already. 异常已经说明了。 You are checking an index that is not in the bounds of the array any more.
您正在检查不在数组范围内的索引。 Look at the second for loop:
查看第二个for循环:
for(int i=0; i<=iGrades.length; ++i)
It runs from 0 to 30. The array only goes from 0 to 29 though. 它的范围是0到30。不过,数组只能是0到29。 You have to use < instead here:
您必须在此处使用<代替:
for(int i=0; i < iGrades.length; i++)
Since arrays are zero-based, this 由于数组是从零开始的,因此
i<=iGrades.length
will allow i
to equal Grades.length
, which is one past the last index of the array. 将允许
i
等于Grades.length
,它比数组的最后一个索引Grades.length
一个。 Use <
. 使用
<
。
Remember 记得
Array Index start from 0 to length of array -1
数组索引从
0 to length of array -1
开始0 to length of array -1
Change the loop accordingly 相应地更改循环
Hint change <=
to <
提示更改
<=
到<
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.