【问题标题】:Why is the code not reachable?为什么无法访问代码?
【发布时间】:2015-03-07 14:06:15
【问题描述】:

以下是在“out.close();”上给我一个“代码无法访问”消息 我找不到问题,因为它与我运行的其他有效代码或多或少相同!

import java.io.*;
import java.net.*;

public class MyClient {
    private static String SERVER = "127.0.0.1";
    private static Integer PORT = 8765;
    public static void main(String[] args) throws IOException {
        // Connect to the server and create the writer and reader
        Socket socket = new Socket(SERVER,PORT);
        PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        // Loop forever
        while(true) {

            out.println("Question:");
            String sum = System.console().readLine();
            out.println(sum);

            String line = in.readLine().trim();
            if(line==null || line.startsWith("Finished")) {
                socket.close();
                return;
            }
            else if (line.startsWith("My answer is: ")){
                System.out.println(line);
                String message = System.console().readLine();//correct or wrong!!
                out.println(message);
            }       
        }
        // Close the in and out and socket
        out.close();
        in.close();
        socket.close();
    }
}

【问题讨论】:

  • 返回需要休息

标签: java unreachable-code


【解决方案1】:

您正在从while 循环中执行return。你应该改用break。

【讨论】:

    【解决方案2】:

    因为代码永远不会到达:

        // Close the in and out and socket
        out.close();
        in.close();
        socket.close();
    

    将return 更改为break:

        if(line==null || line.startsWith("Finished")) {
            socket.close();
            break; //<------------------CHANGE
        }
    

    【讨论】:

      【解决方案3】:

      问题来了

       // Loop forever
              while(true) {
      

      它将永远循环,您永远不会停止它,因此循环之后的下一行将永远不会执行。就是这样:P

      【讨论】:

        【解决方案4】:

        因为您有一个无限循环 (while(true)),没有中断或其他退出方式。

        【讨论】:

          【解决方案5】:

          在循环中使用return 不是一种好方式,但如果想确保释放资源,您可以使用try ... finally 包装循环:

          try {
            while(true) {
              // ...
              if(condition) {
                return;
              }
              // ...
            }
          } finally {
            out.close(); // this is called just before leaving the surrounding function
            // ...
          }
          

          即使在循环内抛出异常,这仍然有效。

          【讨论】:

            猜你喜欢
            • 2018-09-23
            • 2014-04-29
            • 2020-08-27
            • 1970-01-01
            • 2021-10-06
            • 2017-01-02
            • 1970-01-01
            • 2012-04-11
            • 1970-01-01
            相关资源
            最近更新 更多