【问题标题】:Use of nextLine() method after using nextInt() method [duplicate]使用 nextInt() 方法后使用 nextLine() 方法[重复]
【发布时间】:2017-12-19 10:23:33
【问题描述】:

使用nextInt 方法后,我无法使用nextLine 方法。这是下面给出的注释......

黑客等级注意事项:(如果您在nextInt() 方法之后立即使用nextLine() 方法,请记住nextInt() 读取整数标记;因此,该行整数输入的最后一个换行符仍然是在输入缓冲区中排队,下一个nextLine() 将读取整数行的剩余部分(为空)。 nextLine 方法没有被跳过,但它是空的。 代码:

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d=scan.nextDouble();
    String s=scan.nextLine();
    // Write your code here.

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
  }
}

输出: 细绳: 双倍:3.1415 诠释:42

【问题讨论】:

  • 你能给我们看一些代码吗?
  • 向我们显示代码以及您遇到错误的位置。所以我们可以帮助您解决它

标签: java stdin scanning


【解决方案1】:

在 Scanner 类中,如果我们在七个 nextXXX() 方法中的任何一个之后调用 nextLine() 方法,则 nextLine() 不会从控制台读取值,并且光标不会进入控制台,它将跳过该步骤。 nextXXX() 方法是 nextInt()、nextFloat()、nextByte()、nextShort()、nextDouble()、nextLong()、next()。

这是因为 Scanner 类的 nextInt() 方法不会使用您输入的最后一个换行符,因此在下次调用 Scanner 类的 nextLine() 时会使用该换行符。

您可以在 Scanner#nextInt 之后触发一个空白的 Scanner 类的 nextLine() 调用,以使用该行的其余部分,包括换行符

int option = input.nextInt();
input.nextLine();  // Consume newline left-over
String str1 = input.nextLine();

【讨论】:

    【解决方案2】:

    你可以试试这个。

        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
            int x = sc.nextInt();
            double y = sc.nextDouble();
            sc.nextLine();
            String s = sc.nextLine();
    
            System.out.println("String: " + s);
            System.out.println("Double: " + y);
            System.out.println("Int: " + x);
    
    }
    

    【讨论】:

    • 解释:sc.nextDouble 中剩余一个换行符,因此在将 s 分配给包含数据的行 sc.nextLine() 之前,需要 sc.nextLine() 跳过此空白行我们想要。
    【解决方案3】:

    是的,它读取剩余的空行。因此,在给输入传递空格时,您将看到输出,而不是打印字符串打印它的长度

    【讨论】:

      【解决方案4】:

      当您为 nextInt() 输入整数时,您会立即按下 Enter 键,此 Enter 键会被 nextLine() 捕获。 s 商店进入,这被称为空白,所以它不显示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-17
        • 1970-01-01
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多