简体   繁体   English

为什么nextInt()忽略/ n?

[英]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. 使用此代码,输入“ m”不会给我任何问题,但是输入“ f”会使我两次打印两次。 Why exactly does this happen with nextInt() and not with nextLine()? 为什么恰好发生在nextInt()而不是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? 为什么nextInt()忽略\\ n?

It doesn't ignore it. 它不会忽略它。 It just doesn't read it 1 . 它只是不读1

In fact, it is the nextLine method that is the anomalous one here. 实际上, nextLine方法在这里是异常的。 Most of the next methods work by getting the next token and then attempting to parse token. 大多数next方法的工作方式是获取下一个令牌,然后尝试解析令牌。 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. nextLine()方法是不同的。 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! 1-...除非在调用nextInt()它是领先的定界符之一!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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