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"); }
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
OCUP UML fundamental
ITIL foundation
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: why is the error coming only for j not for i?