• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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");
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 2661
19
Netbeans IDE C++ Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic