I am trying to understand how these three methods work. Here's how I understood them:
nextLine()
reads the remainder of the current line even if it is empty.nextInt()
reads an integer but does not read the escape sequence "\n".next()
reads the current line but does not read the "\n".
Suppose I have the following code:
import java.util.Scanner;
public class Welcome2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Next enter two words:");
int n;
String s1, s2;
n = keyboard.nextInt();
s1 = keyboard.next();
s2 = keyboard.nextLine();
System.out.println(" n is " + n + " s1 is " + s1 + " s2 is " + s2);
}
}
If my input is :
2
Hi
Hello
Then I get the following output on screen:
n is 2
s1 is hi
s2 is
Why would s1
have a value of "HI"?
Does this mean that the method next()
reads the next line even though the escape character for the first line has not been read by nextInt()
?