When I run the following code it stops to let me enter servername and them port number, after that it is supposed to stop and let me enter username but it never pauses for scan.nextline() and flies straight to enter reciever name??
public static void main(String[] args) throws IOException {
try {
System.out.println("\n\n\nTCP Chat Client\n\nEnter server name:");
Scanner scan = new Scanner(System.in);
//get server info from user
serverName = scan.nextLine();
System.out.println("\nEnter port number:");
serverPort = scan.nextInt();
System.out.println("Enter your username:\n");
userName = scan.nextLine();
//make connection to server
cSocket = new Socket(serverName, serverPort);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
//send username to server
out.println(userName);
String rcvrname="wefwef";
String message=null;
//start messaging
while(!(rcvrname.equals("exit"))){
System.out.println("Enter reciever name");
out.println(scan.nextLine());
System.out.println("Enter message");
out.println(scan.nextLine());
}
out.close();
in.close();
cSocket.close();
}
Instead of
scan.nextInt(), I would usescan.nextLine()again, and then parse the input. If you get aNumberFormatException, you can bark at the user that the input was invlaid.The reason why you need to do something like this is that you still have a newline sitting at the end of your serverPort input. When you use
nextInt(), the scanner grabs all of the next token and tries to convert it into anInteger. Anything after the Integer token remains to be scanned.To prove this, with your original code, if you put a token separator, like a space, after your server port input and then add some text, you will find that your subsequent
userNameassignment will grab from the end of the number to the next newline.with the input:
will output
This is because the space is acting as a token separator, and after the
scan.nextInt()is called, the space and theabcare still left in the buffer. When the subsequentscan.nextLine()is called, the space and theabcare scanned from the buffer.