如何在Java中每次迭代时清空循环中的缓冲区?

如何在Java中每次迭代时清空循环中的缓冲区?,java,loops,Java,Loops,我正在写一个for循环来填充数组。这是我的代码: for (int i = 0; i < students.length; i++) { System.out.println("Student " + (i+1)); System.out.print("First Name: "); students[i][0] = keyboard.nextLine(); System.out.print("Last Name:

我正在写一个for循环来填充数组。这是我的代码:

for (int i = 0; i < students.length; i++)
    {
        System.out.println("Student " + (i+1));

        System.out.print("First Name: ");
        students[i][0] = keyboard.nextLine();

        System.out.print("Last Name: ");
        students[i][1] = keyboard.nextLine();

        System.out.print("Date of Birth (MM/DD/YYYY): ");
        students[i][2] = keyboard.nextLine();

    }
for(int i=0;i
但是,当我运行时,它会输出以下内容:

名:姓:

并且将只读取一个字符串作为名字和姓氏


这只发生在第一次迭代中,接下来的迭代都很好。我认为这可能与清空缓冲区有关,但为什么它只在第一次发生?

我想知道在调用此代码块之前是否有一个未正确处理的行尾字符。您是否使用扫描仪的任何其他方法,如nextInt()、nextDouble()或next()?如果是这样的话,那么您可能需要在这些方法调用之后调用nextLine()来吞下行尾标记。例如

int myInt = keyboard.nextInt();
keyboard.nextLine();  // call this to swallow end of line character

double myDouble = keyboard.nextDouble();
keyboard.nextLine();

如果我们不知道
键盘
变量是什么,我们就无能为力。你能把初始化的地方贴出来吗?