在Java中的For循环中跳过迭代

时间:2013-11-19 22:36:54

标签: java loops for-loop

我的for循环跳到要进入的二年级,我无法弄清楚为什么会发生这种情况。输出如下:

输入成绩1:输入成绩2:

public static void main(String args[]){

    Scanner inputReader = new Scanner(System.in);
    System.out.print("Would you like to input grades?: ");
    String input = inputReader.next();

    if (input.equals("y")){
        String[] grades =new String[2];

        for (int counter = 0; counter < grades.length; counter++){
            System.out.print("Type in Grade Number " + (counter + 1) + ": ");
            grades[counter] = inputReader.nextLine();
        }
     }
}

2 个答案:

答案 0 :(得分:2)

next()读取一个单词,而不是整行,并且它不会丢弃该单词之后的行,因此当您键入名字时,扫描程序仍在等待消耗其余部分的理由线。只有当你第一次调用nextLine()时它才会这样做(我假设该行的其余部分是空白的)

将您的代码更改为

    String lastName = inputReader.nextLine(); // read the whole line, not just a word
    System.out.print("Student First Name: ");
    String firstName = inputReader.nextLine();

答案 1 :(得分:1)

之后

String firstName = inputReader.next();

您必须致电nextLine()。实际上,next()不会消耗EOL,因此当您在循环的第一次迭代中调用nextLine()时,它会立即在第一个名称后使用EOL。

相关问题