简体   繁体   中英

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? :

Why does nextInt() ignore \\n?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM