首页 > 解决方案 > 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,警告出现在“问题”窗口中。

标签: javavisual-studio-codewhile-loopcompiler-warningsassignment-operator

解决方案


这是相同效果的一个更简单、孤立的实例。

这两种变体都编译为相同的字节码。

在这个例子中,

a += 1;

IDE 看到a被更新 1,但没有看到直接使用a.

在这个例子中,

a = a + 1;

IDE 看到a在表达式中使用a + 1,然后分配回a,因此从 IDE 的角度来看,a已使用。

仅仅为变量赋值并不构成使用。

请注意,此unused行为也存在于 中,Eclipse IDE但可以根据需要禁用。


推荐阅读