Use of nextLine() method after using nextInt() method
In Scanner class , if we
call nextLine() method after any one of the seven nextXXX() method(like nextInt(), nextFloat(), nextByte(),
nextShort(), nextDouble(), nextLong(), next()) then the nextLine() doesn’t read values from console and cursor will not
come into console it will skip that step.
That’s because the Scanner class have buffer memory which
contains escape sequence (/n)
Lets understand with an example:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x
= sc.nextInt();
double y = sc.nextDouble();
//
sc.nextLine();
String s = sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + y);
System.out.println("Int: " + x);
}
Here when we run this code it prints string value but skip the
value of y and take input of x and do not print the value of y this is because
when it takes input by using nextInt() then its value is assign to the ‘x’
variable and escape sequence(/n) resides in the memory .
After that when we try to take next value then /n is assign to
the variable ‘y’ and then take input for string.
When you are entering the integer for nextInt() then immediate
you press enter key and this enter key caught by nextLine(). s stores enter and
that is known as whitespace so it not shows.
In order to overcome this problem, we use
sc.nextLine()
this method stores that /n value and then nextLine() will be able to take input
from the console.
1 Comments
Thank you so much sir for motivating us and will surely come with lots of information.
ReplyDelete