User
User

Reputation: 77

printing the location of a value in a two dimensional array

I defined a two dimensional array which includes some integer numbers. in my program, a user enters a number to search it in the two dimensional array. after finding the number, i want to print the location of the number in the array. but in my program, it cannot print the location of j. how can i correct it?

public static void main(String[] args) {
   int[][] arrayOfInt = {
       {12, 14, 15},
       {56, 36, 48},
       {23, 78, 69,48}
   };
   Scanner input = new Scanner(System.in);
   int search,i,j;
   boolean check = false;
   System.out.print("Enter your number: ");
   search = input.nextInt();
   search:
   for (i=0; i<arrayOfInt.length; i++)
   {
       for(j=0; j<arrayOfInt[i].length; j++)
       {
           if(arrayOfInt[i][j] == search)
           {
               check = true;
               break search;
           }
       }
   }
   if (check)
   {
        System.out.println("i = " + i + " and j = " + j);
   }
   else
   {
       System.out.println("There is not in the array!");
   }
}

Upvotes: 0

Views: 101

Answers (2)

Pankaj Gadge
Pankaj Gadge

Reputation: 2814

Your program lookss good, should not have any problems.

The only thing, is you need to print i+1 & j+1 values in order to print the actual indexes of array. ALso, you need to initialize j at the beginning.

int search,i,j = 0;

if (check)
{
     System.out.println("i = " + (i+1) + " and j = " + (j+1));
}

Upvotes: 1

PakkuDon
PakkuDon

Reputation: 1615

The compiler's complaining about j not being initialised because it'll only be assigned a value if the contents of the outer for-loop are executed.

You can get rid of this error by initialising j to an arbitrary value, like so:

int search, i, j = -1;

Upvotes: 1

Related Questions