简体   繁体   中英

Can't print variable outside for-loop

Why can not I print the value of j in the last statement although the variable j declared outside the for loop as a local variable?

package practicejava;

public class Query {

    public static void main(String[] args) throws java.io.IOException {
      int j;
      for(int i=1;i<=5;i++) {   
          j=i;
          System.out.println(j);
      } 
      System.out.println("j="+j);
    }
}

The compilation error is

The local variable j may not have been initialized

As the compiler complains, you just need to initialize the variable before using it :

int j = 0;

This will resolve the compilation error.

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