java - 如果在主方法中完成声明并在循环内初始化,则在 Java 中无法从 For 循环外部访问变量吗?
问题描述
class Myclass {
public static void main(String[] args) {
int x; // Declared in main method
if (true) {
for (int i = 0; i < 5; i++) {
x = 5;// initialized inside loop
}
}
System.out.println(x);// accessing outside for loop
}
}
这给出了一个错误:变量 x 可能没有被初始化 System.out.println(x); ^ 1 个错误;
但是,下面的代码工作正常
class Myclass {
public static void main(String[] args) {
int x; // Declared in main method
if (true) {
x = 5;// initialized in if block
for (int i = 0; i < 5; i++) {
// x=5;
}
}
System.out.println(x);// accessing outside if loop
}
}
在这两个代码中,唯一的区别是在第一种情况下,变量在“for循环”中初始化,而在第二种情况下,它在“if块”中初始化。那么为什么它会有所作为。请向我解释,因为我无法找到真正的原因。
解决方案
问题是编译器不知道当你访问它时x
会被初始化。那是因为编译器不会检查循环体是否会实际执行(在极少数情况下,即使是这样一个简单的循环也可能不会运行)。
如果条件不总是为真,即如果您使用这样的布尔变量,您的 if 块也是如此:
int x;
boolean cond = true;
if( cond ) {
x = 5;
}
//The compiler will complain here as well, as it is not guaranteed that "x = 5" will run
System.out.println(x);
您作为人类会说“但cond
已初始化true
并且永远不会更改”,但编译器不确定(例如,由于可能的线程问题),因此它会抱怨。如果您要创建cond
一个最终变量,那么编译器将知道cond
在初始化后不允许更改该变量,因此编译器可以内联代码以if(true)
再次有效地拥有。
推荐阅读
- c++ - 如何到达链表中的第 N 个节点?
- python - 无法在 Django 中设置默认表单值
- c# - DataGrid 没有输入的最后一行
- firebase - 之前的日内数据会自动合并到主表吗?
- mongodb - 我正在使用 InetAddress 获取服务器 IP,但它解析为本地主机,因为我的服务器名称与服务器 IP 相同,我该怎么办?
- javascript - POSTMAN 产生错误:错误:整数类型的输入语法无效:尝试发送 POST 请求时
- javascript - 在子组件的 ngAfterViewInit() 中调用时,父组件的元素上的 getElementById 返回 null
- twitter - 如何提高 Twitterbot 请求的预渲染速度?
- scala.js - 有没有办法在脚本标签中运行纯 scala 代码
- flutter - 使用 Flutter 打印到 ESC/POS 时如何防止套接字超时错误