3
class myThread extends Thread {

myThread(Socket socket) {
    Scanner sc = new Scanner(socket);
}

public void run() {
    StringBuilder sb = new StringBuilder();
    try {
        while(sc.hasNext()) {
            sb.append(sc.next());
            sb.append(" ");
        }
        System.out.println(sb.toString());      

    } catch (Exception e) {
        System.out.println(e);      
    }
}

This code doesn't output anything. However, If I move the System.out.println(sb.toString()); into the while loop, it does. I have no idea why this is, but I need the code to output first AFTER the while loop is complete.

How would one go about to print the StringBuilder.toString() after the while-loop is complete?

1
  • 5
    I strongly suspect that the problem is that the loop isn't ending, because the socket isn't being closed. Commented Feb 23, 2016 at 22:02

1 Answer 1

5

The socket is probably never being closed, and the scanner is just blocking on hasNext().

Close the socket and it should finish.

Sign up to request clarification or add additional context in comments.

1 Comment

Works now. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.