Java - Scanner - 跳过我上一个nextLine()请求

时间:2014-07-16 00:56:02

标签: java java.util.scanner

所以我早些时候实例化了Scanner scan,但它在scan.nextLine()之后跳过我的第二个scan.nextInt()。我不明白为什么会跳过它?

     System.out.println("Something: ");

        String name = scan.nextLine();

        System.out.println("Something?: ");

        int number = scan.nextInt();

        System.out.println("Something?: ");

        String insurer = scan.nextLine();

        System.out.println("Something?: ");

        String another = scan.nextLine();

4 个答案:

答案 0 :(得分:7)

因为输入数字时

    int number = scan.nextInt();

你输入一些数字并点击输入,它只接受数字并在缓冲区中保留换行符号

所以nextLine()只会看到终结符字符,它会假设它是空白字符串作为输入,要修复它,在处理scan.nextLine()之后添加一个int

例如:

 System.out.println("Something?: ");

 int number = scan.nextInt();

 scan.nextLine(); // <-- 

答案 1 :(得分:4)

当您致电int number = scan.nextInt();时,它不会消耗已推送的回车符,所以这是在下一个scan.nextLine();

您希望代码

    ....
    System.out.println("Something?: ");
    int number = scan.nextInt();
    scan.nextLine();                      // add this
    System.out.println("Something?: ");
    String insurer = scan.nextLine();

答案 2 :(得分:4)

*方法nextInt()不会消耗新的行字符\ n。所以新的行字符是  已经存在于缓冲区中,而nextInt()将被忽略。

*接下来当你在nextInt之后调用nextLine()时,nextLine()将使用旧的新行
 留下的角色考虑结束,跳过其余部分。

enter image description here

解决方案

int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();

System.out.println("Something?: ");
String insurer = scan.nextLine();

OR

//将字符串明确地解析为interger

String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();

int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();

答案 3 :(得分:1)

之前给出的所有答案或多或少都是正确的。

这是一个紧凑版本:

您想要做什么:首先使用nextInt(),然后使用nextLine()

发生了什么:当nextInt()等待您的输入时,您在键入整数后按ENTER键。 问题是nextInt()识别并只读取数字,因此\n键的ENTER会留在控制台上。 当nextLine()再次出现时,您希望它等到找到\n。但是你没看到的是\n由于nextInt() 的不稳定行为已经在控制台上[这个问题仍然作为jdk8u77的一部分存在]。

因此,nextLine读取空白输入并向前移动。

解决方案:每次使用scannerObj.nextLine() 后始终添加scannerObj.nextInt()

相关问题