Loop疯了

时间:2013-09-10 15:00:23

标签: java loops while-loop

即使我输入有效的输入而且找不到它有什么问题,这个循环仍然会给我我的错误信息。它与程序中的其他循环相同,都可以正常工作。有谁知道这个问题?这是循环:

System.out.println("Male or Female (M/F)");
    gender = userInput.next().charAt(0);
    gender = Character.toLowerCase(gender);

    while((gender != 'm') || (gender != 'f')) {
        System.out.println("ERROR Please enter a valid age");
        System.out.println("Male or Female (M/F)");
        gender = userInput.next().charAt(0);
        gender = Character.toLowerCase(gender);
    }//end while

现在,如果我输入“m”或“f”,它会给我错误信息吗? ??? ???

1 个答案:

答案 0 :(得分:6)

while((gender != 'm') || (gender != 'f')) {

应该是

while((gender != 'm') && (gender != 'f')) {

条件(gender != 'm') || (gender != 'f')始终评估为true。要了解原因,请考虑一个案例 - gender = 'm' ...

(gender != 'm') || (gender != 'f')
('m'    != 'm') || ('m'    != 'f')
false           || true
true

基本上,java不知道常用的英语习语if gender isn't (either) male or female