Entering an integer input in java?

Here is the code that i wanted to run but here i have a problem 

The output was as following :

Enter your name : Sam

Enter your age : 19

Enter your Last name : Sam

Why after entering 19 and pressing enter the program didnt ask me to enter last name 

But it automatically took value of lastName variable as a space(?) 

But it didnt happen at first when i entered the value of variable name and i pressed enter it asked me for value of age 

P.s: i am new to java and havent studied concepts like loop array oop etc... so please explain in sinple terms if possible

Attachment image

1 Answer

  • 1 month ago
    Favorite Answer

    You are mixing line-oriented input (the .nextLine() method) and token-oriented input (all of the other .next???() methods).

    The problem is that the Scanner object reads tokens up to, but not including the delimiter (usually a space or newline) that ends the token.  So, if you typed 19 followed immediately by Enter or Return, then the sc.nextByte(); call reads the '1' and '9' characters, but does *not* read the '\n' that follows.

    That's not a problem with all token-oriented input.  The next sc.next???() call will skip over leading blanks, tabs and newlines to find a nonblank character to start the token.

    However, when a sc.nextLine() call follows, that call sees the '\n' and interprets that as an empty line.  It read up to, and including, the newline that ends the line, returning an empty string and discarding the newline.

    Each time you switch from token-oriented input to reading whole lines, you need to put in an extra .nextLine() call to get rid of the end of line from the previous token.  You don't need to store it.  Just write:

        sc.nextLine(); // discard end of previous line

        String lastName = sc.nextLine();

    That should fix the runaway input.

Still have questions? Get your answers by asking now.