• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is the error coming only for j not for i?

 
mony monk
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is the program code and the error is in the last print statement stating that j is not initialized. I didn't initialize i as well then why is it looking only for j? can any one explain please.

class Demo {
public static void main(String[] args) {
int numbers[][] = { {12, 14, 65},
{2213, 242, 43},
{112, 34, 21, 2}
};
int search = 21;
int i,j;
boolean found = false;
look:
for (i=0; i<numbers.length; i++) {
for (j=0; j<numbers[i].length; j++) {
if (numbers[i][j] == search) {
found = true;
break look;
}
}
}
if (found == true) System.out.println(search + " found at index " + i + "," + j);
else System.out.println(search + " not found");
}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
j is assigned a value inside the body of another for loop. If the body of that outer loop never executes, then j will never be assigned a value.
 
Jan Cumps
Bartender
Posts: 2599
12
C++ Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code for (i=0; i<numbers.length; i++) { is on the same nesting level as if (found == true) System.out.println(search + " found at index " + i + "," + j);.
So java knows that i has been initialized (i=0).

However, the code for (j=0; j<numbers[i].length; j++) is nested inside the 'for i' loop.
For the java compiler, it is not guaranteed that that line will be called.


Regards, Jan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic