user3559500
user3559500

Reputation: 41

how does nextLine discard the input?

I'm a beginner at java. I wanted to know how the nextLine() Method discards your current input? For example assume the following code:

Scanner input = new Scanner(System.in);
int a = input.nextInt();
input.nextLine();

After the input.nextLine() is executed, the value in "input" is discarded. I wanted to know how does it work?

Upvotes: 3

Views: 1495

Answers (2)

user1946492
user1946492

Reputation: 31

input is an object representing a scanner. When nextLine is executed, the function reads until a newline character is encountered, deposits that data into a buffer and returns the buffer. The important point to note is that "input" doesn't store any data. It stores a representation of a file and a position within that file from which you are reading. Therefore nothing in input is discarded. Rather you are simply not using the value returned by nextLine, but the side effect of the nextLine function still increments the input object's location within the file.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240928

when you enter number and press Enter, It reads integer value to a and keeps \n in buffer

Now when you invoke nextLine() it directly gets newline character from buffer skipping user's input

to avoid it put next() method call to read left over \n from buffer before invoking newLine()and after successful execution of nextInt()

Upvotes: 3

Related Questions