我有一个简单的聊天应用程序中的大量代码,但这不是这个问题的重要部分。在我看来,这是代码的一部分,应该无法访问:

while (!end) {
            outputToServer.println(consoleInput.readLine());
        }

        communicationSocket.close();

    } catch (Exception e) {
        // TODO: handle exception
    }
}

@Override
public void run() { // receiving message from other clients

    String serverTextLine;

    try {
        while ((serverTextLine = inputFromServer.readLine()) != null) {
            System.out.println(serverTextLine);

            if (serverTextLine.indexOf("*** Goodbye") == 0) {
                end = true;
                return;
            }
        }

    } catch (Exception e) {

    }

}


我不明白的是,当使用while作为条件的while循环在前面时,程序将如何到达其中将“ end”变量设置为true的代码的一部分...我想它是一些基本的我不记得的Java东西,或者我一直忽略的东西:)帮助,好吗?

最佳答案

如代码所示,控件将到达该行

end = true;


当条件

serverTextLine.indexOf("*** Goodbye") == 0


返回true !,

即方法indexOf(String)返回:字符串中子字符串的索引(如果存在),如果未找到则返回-1!

仅当字符串以子字符串开头时,才将“ 0”作为索引。即,当serverTextLine以“ ***再见”开头时。

10-08 14:02