Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Scanner - Skips over my last nextLine() request [duplicate]

So I instantiate the Scanner scan a lot earlier but it skips right over my second scan.nextLine() after scan.nextInt(). I don't understand why it skips over it?

     System.out.println("Something: ");

        String name = scan.nextLine();

        System.out.println("Something?: ");

        int number = scan.nextInt();

        System.out.println("Something?: ");

        String insurer = scan.nextLine();

        System.out.println("Something?: ");

        String another = scan.nextLine();
like image 202
user3590149 Avatar asked Mar 27 '26 05:03

user3590149


2 Answers

because when you enter a number

    int number = scan.nextInt();

you enter some number and hit enter, it only accepts number and keeps new line character in buffer

so nextLine() will just see the terminator character and it will assume that it is blank String as input, to fix it add one scan.nextLine() after you process int

for example:

 System.out.println("Something?: ");

 int number = scan.nextInt();

 scan.nextLine(); // <-- 
like image 122
jmj Avatar answered Mar 29 '26 20:03

jmj


When you call int number = scan.nextInt(); it does not consume the carriage return that has been pushed, so this is does at the next scan.nextLine();

You want your code to be

    ....
    System.out.println("Something?: ");
    int number = scan.nextInt();
    scan.nextLine();                      // add this
    System.out.println("Something?: ");
    String insurer = scan.nextLine();
like image 25
Scary Wombat Avatar answered Mar 29 '26 20:03

Scary Wombat