File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes why is the error coming only for j not for i? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why is the error coming only for j not for i?" Watch "why is the error coming only for j not for i?" New topic
Author

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

mony monk
Greenhorn

Joined: May 02, 2007
Posts: 3
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

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jan Cumps
Bartender

Joined: Dec 20, 2006
Posts: 2499
    
    8

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 and ITIL foundation
youtube channel
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why is the error coming only for j not for i?