Java Scanner在字符串之前不接受整数输入

时间:2015-01-11 07:30:56

标签: java java.util.scanner

    public static void main(String[] args) {

       Student[] test = new Student[7];

      for (int i = 0; i < 7; i++) {
        test[i] = new Student();

        Scanner kb = new Scanner(System.in);
        System.out.println("What is the Students ID number?: ");
        test[i].setStudentId(kb.nextInt());
        System.out.println("What is the Students name?: ");
        test[i].setStudentName(kb.nextLine());
      }

    }

在上面的程序中,当我首先尝试取整数输入时它会跳过字符串输入,但在同一程序中,如果我首先保持字符串输入,它可以正常工作。这背后可能是什么原因?

        Scanner kb = new Scanner(System.in);

        System.out.println("What is the Students name?: ");
        test[i].setStudentName(kb.nextLine());
        System.out.println("What is the Students ID number?: ");
        test[i].setStudentId(kb.nextInt());

程序的输出将是

学生证号码是多少?: 1

学生姓名是什么?://我不会让我在这里输入字符串

学生证号码是什么?:

但是当我在字符串上方输入Integer时它工作正常。可能是什么原因?

2 个答案:

答案 0 :(得分:3)

nextInt()的调用只读取整数,行分隔符(\n)留在缓冲区中,因此对nextLine()的后续调用只会读取,直到行分隔符已经存在。 解决方案是使用nextLine()作为ID,然后使用Integer.parseInt(kb.nextLine())将其解析为整数。

答案 1 :(得分:0)

调用nextInt()后,扫描程序已超过整数,但未超过输入整数的行的末尾。当您尝试读取ID字符串时,它会读取该行的其余部分(为空白),而不等待进一步的输入。

要解决此问题,只需在致电nextLine()后向nextInt()添加电话。

System.out.println("What is the Students ID number?: ");
test[i].setStudentId(kb.nextInt());
kb.nextLine(); // eat the line terminator
System.out.println("What is the Students name?: ");
test[i].setStudentName(kb.nextLine());
相关问题