Getting User input with Scanner

Posted by Giannis on Stack Overflow See other posts from Stack Overflow or by Giannis
Published on 2012-10-21T16:44:03Z Indexed on 2012/10/21 17:00 UTC
Read the original article Hit count: 242

Filed under:
|

I am trying to have a scanner take input in a loop. Once the user wants to finish he can exit this loop. I have tried many different ways to do it but there is always some problem. This is the code:

        Scanner sc = new Scanner(System.in);
        System.out.println("Continue?[Y/N]");
        while (sc.hasNext()&& (sc.next().equals("Y"))) {
                System.out.println("Enter first name");
                String name = sc.nextLine();
                System.out.println("Enter surname");
                String surname = sc.nextLine();
                .
                .
                .
                System.out.println("Continue?[Y/N]");
            } 
        }

The problem with the code above, which also happens on different methods I tried, is that when the user types Y, the scanner will skip the first input for first name,and jump to the surname. If the user types N the loop stops correctly. Someone can explain the reason this happens, and how to overcome using scanner class?

p.s: Doing something like while(sc.nextLine().equals("Y")), will cause the loop to terminate before getting input from user after first run of the loop.

© Stack Overflow or respective owner

Related posts about java

Related posts about java-util-scanner