Java解决在nextInt()后使用nextLine()的方法

Ref: Scanner is skipping nextLine() after using next() or nextFoo()?

如果在nextInt()方法之后立即使用nextLine()方法,请记住nextInt()读取整数标记; 因此,该行整数输入的最后一个换行符仍在输入缓冲区中排队,下一个nextLine()将读取整数行的剩余部分(为空)。

  • 在调用了nextInt()后,我们可以先调用一次nextLine(),将该行剩下的内容抛弃;

    1
    2
    3
    int i = input.nextInt();
    input.nextLine();//抛弃输入整数时最后的换行符
    String str = input.nextLine();
  • 全部都使用nextLine()读入,然后将其读入的数据转换为Integer。

    1
    2
    3
    4
    5
    6
    7
    int i = 0;
    try {
    i = Interger.prseInt(input.nextLin());
    } catch (NumberFormatException e){
    e.printStackTrace();
    }
    String str = input.nextLine();