为什么我会收到警告 "dead code"?

Why do I get warning "dead code"?

public class DeadCodeInLuna {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String string;
        for (string = in.readLine(); !string.equals(""); string=in.readLine()) {
            if(string == null) { 
               System.out.println("null while reading response!");
            }
        }
    }
}

因为如果 !string.equals("") 的计算结果为 true,则 string 永远不会是 null

换句话说,当!string.equals("")true时,string保证不是null,否则会出现NullPointerException

因为在代码的那一点,string 不能为空。如果它从 in.readLine() 出来 null,你会在 for.

的条件检查中得到 NullPointerException

改为

    for(string=in.readLine();!"".equals(string);string=in.readLine())
        if(string==null) System.out.println("null while reading response!");
    }

无论 string 是否为 null,equals 都会起作用,您会看到警告消失。

根据你的情况,你会避免string == null

for (string = in.readLine(); !string.equals(""); string=in.readLine()) {
//                           ^--------> here!!!

所以if(string == null)是多余的,永远不会是真的