简体   繁体   中英

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.

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. 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(int i=0; i<=iGrades.length; ++i)

It runs from 0 to 30. The array only goes from 0 to 29 though. 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. Use < .

Remember

Array Index start from 0 to length of array -1

Change the loop accordingly

Hint change <= to <

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM