[英]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.