-3

How can I use a for loop to return the index number of the location of the integer I want to find? For example, in the array above, if the number to “find” is 9, the program should return the index number “5” in a user-friendly phrase.

import javax.swing.JOptionPane;
public class ComparingStrings
{
   public static void main( String[] args )
   {
       int [] array = {-9, 2, 3, 4, 7, 9, 10, 23, 45, 67};
       int index = -1;

       for(int i = 0; i < array.length; i++)
       {
            System.out.print(array[i] + " ");            
       }
       System.out.print( "\n" );
       for(int i = array.length - 1; i > 0; i--)
       {
           System.out.print(array[i] + " ");          
       }
       System.out.print( "\n" );

       String statement = JOptionPane.showInputDialog( "Type the integer which you want to find the location of" );
       int interger = Integer.parseInt(statement);
       System.out.println( "Integer:" + interger );
       for(int i = array.length - 1; i >= 0; i--)
       {
           if( statement .equals (array[i]))
           {
               index = i;
               System.out.println( "Index of Integer is: " + i);
           }
           else
           {
               System.out.println( "Index of Interger is: -1" );
           }
       }
    }//end method main
}//end class ComparingStrings
Hannah
  • 1
  • 2
  • 2
    why there is `i--` – Pavneet_Singh Nov 07 '17 at 07:58
  • 2
    The second `for` loop will go into negative indexes, which will always be out-of-bounds for an array. – Kraylog Nov 07 '17 at 07:58
  • 1
    The error is in this line `for(int i = 0; i < array.length; i--)`. It should be `for(int i = 0; i < array.length; i++)` – Karan Nov 07 '17 at 07:58
  • You'll need to compare an input to the element of the array, and then print `i` itself if they are equal. – Kraylog Nov 07 '17 at 07:59
  • 3
    I don't see any attempt to do what you are describing in this code. You say that you want to find a number and print its index, but you are just printing the array entries twice (with an error in the second loop that goes into negative indices). – Matthew Nov 07 '17 at 08:00
  • "_How can I use a for loop to traverse the array and return the index number of the location of the integer I want to find._" well you should start by declaring a value you want to find and search for it. Your code don't match your requirements – AxelH Nov 07 '17 at 08:03
  • Question has been updated. – Hannah Nov 07 '17 at 09:03

1 Answers1

0

You need to initialize the array with len -1 i.e int i = array.length-1

   for(int i = array.length-1; i >=0; i--)
   {
        if(array[i]==noToFind)
        {
              break;//come out of loop when u find the exact match
        }
   }
   System.out.println("We found no at index = " + i);