[英]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? 为什么我不能在最后一个语句中打印j
的值,尽管变量j
在for循环外声明为局部变量?
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 局部变量j可能尚未初始化
As the compiler complains, you just need to initialize the variable before using it : 正如编译器抱怨的那样,您只需在使用它之前初始化变量:
int j = 0;
This will resolve the compilation error. 这将解决编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.