0

the following is giving me a "code unreachable" message on 'out.close();' I can't find the issue as it is more or less identical to other code I have run which worked!

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();
    }
}
Mat
  • 202,337
  • 40
  • 393
  • 406

5 Answers5

4

You are doing a return from within the while loop. You should do break instead.

Abhijit
  • 895
  • 5
  • 11
1

Because the code never gets to :

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

Change return to break:

    if(line==null || line.startsWith("Finished")) {
        socket.close();
        break; //<------------------CHANGE
    }
PanTau
  • 73
  • 1
  • 7
0

Here's the problem

 // Loop forever
        while(true) {

It'll loop forever, you never stop it so the next line after the loop will never be executed. That's it :P

Szab
  • 1,263
  • 8
  • 18
0

Because you have an infinite loop (while(true)) with no break or other means of exit.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

It is not a good style to do a return inside a loop, but if want to be sure to free resources you can wrap your loop with a try ... finally:

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

This works even if there is an exception thrown inside the loop.

vanje
  • 10,180
  • 2
  • 31
  • 47