简体   繁体   中英

Nested “For” loop java - how to initialize both variables “i” and “j”?

Let me explain myself: I have the following loop:

int i=0;
int j=0;
for (; i < 6; i++) {
  for (; j < 12 - i; j++) {
    **code**
  }
}
System.out.println(i * j);

This is not working well. It does print 72, but it does not print well the circle that I draw inside the loops. I'm trying to draw 72 circle, the first line will have 12 circle, the line underneath 11, and so on. When I write the code that is above, it only draw the first line of 12 circles and that's it.

I also tried writing "int i=0" and "int j=0" inside the barracks but it did not work because it shows me an error of "the j variable might not have been initialized":

I just want to to draw 6 lines (i is for the lines - first loop) and 12/11/10/9/8/7/6 circles in each line (j is for that - second loop) and also calculate the i*j outside the loop.

Thanks.

You have to set i and j to zero in the for loop as well, otherwise the j iterators are never reset to zero for each i iteration.

public class HelloWorld{
     public static void main(String []args){
        int i=0;
        int j=0;
         for (i=0; i < 6; i++) {
            System.out.println("i  " + i);
            for (j=0; j < 12 - i; j++) {
              System.out.println("j" + j);
            }
        }
        System.out.println(i * j);
     }
}

You are declaring two variables i & j before both the loops getting start, but you should initialize those variables into the loops because of the when the values of the variables increased by loops, it matters.

int i,j;
for (i=0; i < 6; i++) {
     for (j=0; j < 12 - i; j++) {
        **code**
     }
  }
  System.out.println(i * j);

You can define the i and the j values within the for loop declaration:

int i, j;
for(i = 0; i < 6; i++){
    for (j = 0; j < 12 - i; j++) {
          **code**
    }
}
System.out.println(i * j);

If you initialize a variable within a loop, it can only be seen within that loop. This is called scope. I recommend reading about loop scope for Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM