java - vscode:在“while ((inputLine = in.readLine()) != null)”-循环中。x = x + a 没有警告。与:x += a“未使用局部变量的值”
问题描述
以下是来自https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html的示例,唯一的变化是 String inputLine 的内容被添加到 strAll String 而不是打印它,见 X_HERE。
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
String strAll = "";
while ((inputLine = in.readLine()) != null)
// System.out.println(inputLine);
strAll = strAll + inputLine; // X_HERE
in.close();
}
}
这不会引发任何警告。如果将行 X_HERE 替换为
strAll += inputLine;
使用“加法分配”你会得到警告:
未使用局部变量 strAll 的值
如果将 while 条件替换为 (true),strAll 的警告就会消失。为什么在这种情况下对“加法赋值”有不同的处理?
感谢@Joni 编辑:我正在使用 Visual Studio Code,警告出现在“问题”窗口中。
解决方案
这是相同效果的一个更简单、孤立的实例。
这两种变体都编译为相同的字节码。
在这个例子中,
a += 1;
IDE 看到a
被更新 1,但没有看到直接使用a
.
在这个例子中,
a = a + 1;
IDE 看到a
在表达式中使用a + 1
,然后分配回a
,因此从 IDE 的角度来看,a
已使用。
仅仅为变量赋值并不构成使用。
请注意,此unused
行为也存在于 中,Eclipse IDE
但可以根据需要禁用。
推荐阅读
- javascript - React-Select : 在 React-Select 中获取默认值
- c++ - 使用 Crypto++ 的 AES 实现
- mysql - 在一行中获取 2 行值的结果
- java - 在与主应用程序不同的上下文路径和端口上公开一组端点
- python - Python 3.6.3:turtle 库中是否有与 root.after 做同样事情的方法?
- postgresql-9.5 - 在 postgres 函数中如何从 postgres 命令提示符中的异常块返回值
- scala - 使用 udf 和递归在数据框中创建新列
- java - 系统托盘上的空白图标
- linux - 无法在 Ubuntu 上更改 Maven 主页
- javascript - Laravel:当复选框状态更改时发送 AJAX POST 请求时出现问题