【问题标题】:Java Scanner why is nextLine() in my code being skipped? [duplicate]Java Scanner 为什么我的代码中的 nextLine() 被跳过? [复制]
【发布时间】:2011-09-11 11:56:49
【问题描述】:
    Scanner kb = new Scanner(System.in);
    System.out.println("Inserting L");
    int L = kb.nextInt();   
    System.out.println("Inserting N");
    int N = kb.nextInt();
    System.out.println("Inserting x");
    String x = kb.nextLine();
    System.out.println(x);
    System.out.println("You inputed L,N,x");

为什么这段代码没有提示nextLine()

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    用途:

    String x = kb.next();
    

    而不是kb.nextLine()

    这是因为nextInt() 只读取数字,而不是行尾或数字之后的任何内容。当您调用 nextLine() 时,它会读取同一行的其余部分并且不等待输入。

    理想情况下,您应该在nextInt() 的代码之后调用kb.nextLine() 以忽略该行的其余部分。

    【讨论】:

    • +1 用于解释输入缓冲区中剩余的字符。
    【解决方案2】:
    Scanner kb = new Scanner(System.in);
        System.out.println("Inserting L");
        int L = kb.nextInt();   
        System.out.println("Inserting N");
        int N = kb.nextInt();
        System.out.println("Inserting x");
        String x = kb.next();
        System.out.println(x);
        System.out.println("You inputed L,N,x");
    

    试试这个...

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2015-05-06
      • 2014-09-24
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多