扫描仪 nextInt() 与 nextLine() 从控制台读取....为什么我可以在没有 nextLine() 的情况下使用 nextInt()?

Scanner nextInt() vs nextLine() reading from console .... why can I use nextInt() without nextLine()?

为什么我在单独的行中向控制台输入数字时不必使用 nextLine?我希望控制台解释每行的末尾都有 \n,但无论我在每个 nextInt() 之后使用 nextLine(),程序的工作方式都是一样的。使用 Eclipse。

// Example used
10 5      // # lines to read ,  divisor
22        //  if # divisible by divisor, count++ 
15 
10 
25 
17 
13 
15 
10 
7 
9 

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int n = getNumber(keyboard);
    int k = getNumber(keyboard);
    int numLinesPassed = getNumberPassCriteria(keyboard, n, k);
    System.out.println("# Passed: " + numLinesPassed);
}
    
public static int getNumber(Scanner keyboard) {
    return keyboard.nextInt();
}
    
public static int getNumberPassCriteria(Scanner keyboard, int n, int k) {
    int counter = 0;

    for(int i = 0; i < n; i++) {
        int value = keyboard.nextInt();
        if (value % k == 0) {
            counter++;
        }
        //keyboard.nextLine();    not understand why I don't need this 
    }

    return counter;
}

因为 Scanner 的默认分隔符是这种模式

\p{javaWhitespace}+

(注意:没有明确记录这个确切的模式,但是当您实例化一个没有明确指定不同分隔符的情况时,调用 Scannerdelimiter() 方法是您获得的结果)

编辑

根据 user15244370's suggestion this mess of references I made is actually documented directly in the Scanner documentation here。您可以直接跳到下面的列表。


该模式的含义记录在 Pattern class which itself refers to the Character.isWhitespace 方法的文档中 该模式表示

中至少一个的序列
  • 一个 Unicode space 字符(SPACE_SEPARATOR、LINE_SEPARATOR 或 PARAGRAPH_SEPARATOR)但也不是不间断的 space ('\u00A0 ', '\u2007', '\u202F')。 *'\t', U+0009 横向制表。
  • '\n', U+000A 换行。
  • '\u000B',U+000B 竖排表.
  • '\f', U+000C FORM FEED.
  • '\r', U+000D 运输 RETURN.
  • '\u001C', U+001C 文件分隔符。
  • '\u001D', U+001D 组分隔符。
  • '\u001E', U+001E 记录分隔符。
  • '\u001F', U+001F 单位分隔符。

其中包括换行符(第二个要点)。

可能与 Scanner is skipping nextLine() after using next() or nextFoo()? 相混淆。

只有当您正在阅读或尝试使用 nextLine 阅读数字后的下一行时才会出现问题。

为什么? nextInt 读取一个标记,定义为分隔符s 之间的文本(默认白色 space 包括换行和回车 return),这意味着,如果输入以一个或多个定界符开头,这些将被忽略(丢弃)。 nextLine 不读取标记,它只读取换行符;因此,如果下一个字符是换行符,则为空字符串 returned.

易于测试:只需在数字之间输入几行空行 - 您的代码应该可以毫无问题地读取它们。