代码双重打印一行

时间:2016-05-04 18:20:43

标签: java

    char grade;
    for(int x=1; x<6; x++){
        System.out.print("Please enter your course grade here: ");
        grade = (char) System.in.read();
    }
    System.out.println("Thank you! Keep up the good work!");
}

这就是我的代码,似乎没错,但这是输出。

Please enter your course grade here: A
Please enter your course grade here: Please enter your course grade here: A
Please enter your course grade here: Please enter your course grade here: A
Thank you! Keep up the good work!

顺便说一下,我输入了A. 所以你们中有谁知道为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

char grade;
for(int x=1; x<6; x++){
    System.out.print("Please enter your course grade here: ");
    grade = (char) System.in.read();
    while (grade == '\n')
        grade = (char) System.in.read();
}
System.out.println("Thank you! Keep up the good work!");
}

但它没有经过考验。理论上它应该忽略任何换行。