Andrew the Programmer Andrew the Programmer - 1 month ago 4
Java Question

Why Does nextInt() Ignore /n?

I ran into a problem with my code that I thankfully was able to resolve with another similar question here, but I'm curious as to why this occurs.

Here's a simplified version of my program:

public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();

while(!input.equals("x")){

if(input.equals("m")){
String temp = scan.nextLine();
String entry = scan.nextLine();
}
else if(input.equals("f")){
String color = scan.nextLine();
int nothing = scan.nextInt();
}

System.out.println("Enter 'm' for mascara, 'f' for foundation, 'x' to exit");
System.out.println("Entry? :");
input = scan.nextLine();
}
}


With this code, inputting 'm' will not give me any problems, but 'f' will cause me to print our the two lines twice. Why exactly does this happen with nextInt() and not with nextLine()?

'm'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
'f'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :

Answer

Why does nextInt() ignore \n?

It doesn't ignore it. It just doesn't read it1.

In fact, it is the nextLine method that is the anomalous one here. Most of the next methods work by getting the next token and then attempting to parse token. Getting the next token means:

  1. skipping all leading delimiter characters (by default, whitespace)
  2. reading characters upto, but not including the next delimiter character.

The nextLine() method is different. It simply reads all characters up to and including the next end-of-line sequence.


1 - ... unless it is one of the leading delimiters at the point that nextInt() is called!

Comments