This is because you are using the Scanner#next method. And if you look at the documentation of this method, it will return the next token.
So, when you read user input using the next method, it does not read newline at the end. Then it is read by nextLine() inside the while . So your firstName contains newline without your knowledge.
So you should use nextLine() in yours, not next() .
Similarly with nextInt . It also does not read a new line. That way, you can read use readLine and convert it to int using Integer.parseInt . It can throw a NumberFormatException if the input value cannot be converted to int . Therefore, you need to handle it accordingly.
You can try the code below: -
Scanner sc = new Scanner(System.in); System.out.println("Continue?[Y/N]"); while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here System.out.println("Enter first name"); String name = sc.nextLine(); System.out.println("Enter surname"); String surname = sc.nextLine(); System.out.println("Enter number"); int number = 0; try { number = Integer.parseInt(sc.nextLine()); } catch (IllegalArgumentException e) { e.printStackTrace(); } System.out.println("Continue?[Y/N]"); }
But note that if you enter a value that cannot be passed to Integer.parseInt , you will get an exception and this entry will be skipped. In this case, you need to process it using a while .
Or, if you do not want to perform this exception handling : -
You can add empty sc.nextLine() after sc.nextInt() , which will consume newline left, for example:
// Left over part of your while loop String surname = sc.nextLine(); System.out.println("Enter number"); int number = sc.nextInt(); sc.nextLine(); // To consume the left over newline; System.out.println("Continue?[Y/N]");
Rohit jain
source share