首页 > 解决方案 > if 语句中的多个条件 - first 始终为真

问题描述

为什么第一个if陈述总是正确的?

private String setDepartment (){
   int code = Integer.parseInt(JOptionPane.showInputDialog("Enter The Department Code:\n" +
            "1:Sales\n" +
            "2:Development\n" +
            "3:Accounting\n" +
           "4:None"));

    /*Why this if statement is always true? How do i solve it? */
    if (code !=1 || code !=2 || code !=3 || code !=4)
    {
        JOptionPane.showMessageDialog(null, "Invalid Number.Enter a number between 1-4");
        setDepartment();
    }

    if (code==1){
        return "Sales";
    }
    else if (code==2){
        return "Development";
    }
    else if (code==3){
        return "Accounting";
    }
    else
        return "";
    }

标签: javaif-statement

解决方案


替换||&&

if (code !=1 && code !=2 && code !=3 && code !=4)

推荐阅读