2

I am working on java messaging service (Twitter style) in cmd.

I have a message client, where I capture user command / argument.

First argument and command for example could be "login pete" and that would work.

However typing "open mike" afterwards to open mike's channel gives me input mismatch exception.

Code

public class MessageClient {
    public static void main(String[] args) throws IOException {

        /*
         * if (args.length != 2) { System.err.println(
         * "Usage: java EchoClient <host name> <port number>"); System.exit(1); }
         */

        /*
         * String hostName = args[0]; int portNumber = Integer.parseInt(args[1]);
         */
        String hostName = "localhost";
        int portNumber = 12345;

        try (
            Socket messageSocket = new Socket(hostName, portNumber);
            PrintWriter out =
                new PrintWriter(messageSocket.getOutputStream(), true);
            Scanner in = new Scanner(messageSocket.getInputStream());
            BufferedReader stdIn =
                new BufferedReader(
                    new InputStreamReader(System.in))
        ) {

            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                // Read number of response lines (and skip newline character).
                int n = in.nextInt(); // Input mismatch happens here

                in.nextLine();
                // Read and print each response line.
                for (int i = 0; i < n; i++)
                    System.out.println(in.nextLine());


            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        }
        finally {
            System.exit(1);
        }
    }
}
Jaro
  • 23
  • 3

1 Answers1

0

Replace

int n = in.nextInt(); // Input mismatch happens here
in.nextLine();

with

int n = Integer.parseInt(in.nextLine());

Check this for a detailed discussion.

[Update]

If you are not comfortable with using the debugger, you can check the value captured by in.nextLine() as follows:

String n = in.nextLine();
System.out.println(n);
int n = Integer.parseInt(n);

This will give you an idea where the problem is.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72