如果两个复选框都被选中怎么办?

What if both the Checkboxes are selected?

在这个程序中,如果两个复选框都为 selected.It 的条件仍然显示 40% 的价格,而它应该显示 50%,我无法满足第三个 else。

int p      = Integer.parseInt(jTextField1.getText()); //Product Price
int dis    = 40*p/100; // 40% discount
int adis   = 10*p/100; // 10% discount
int tdis   = 50*p/100; // 50% discount
int fpd    = p-dis;    // final price (40% discount)
int fpad   = p-adis;   // final price (10% discount)
int fptdis = p-tdis;   // final price (50% discount)

if (jCheckBox1.isSelected()==true)
    jLabel3.setText("dis is 40% "+"dis amt is "+dis+"final price is "+fpd);
else if (jCheckBox2.isSelected()==true)
    jLabel3.setText("dis is 10% "+"dis amt is "+adis+"final price is "+fpad);
// This condition is not working!!
else if (jCheckBox1.isSelected()==true && jCheckBox2.isSelected()==true)
    jLabel3.setText("dis is 50% "+"dis amt is "+tdis+"final price is "+fptdis);
else jLabel3.setText("no discount"+"final price is "+p);

您应该重新排序您的 if else。首先检查两者,然后检查个人。因为如果检查其中任何一个,检查会在前两个条件本身停止。

    if (jCheckBox1.isSelected() && jCheckBox2.isSelected())
        jLabel3.setText("dis is 50% "+"dis amt is "+tdis+"final price is "+fptdis);
    else if (jCheckBox1.isSelected())
        jLabel3.setText("dis is 40% "+"dis amt is "+dis+"final price is "+fpd);
    else if (jCheckBox2.isSelected())
        jLabel3.setText("dis is 10% "+"dis amt is "+adis+"final price is "+fpad);

    else jLabel3.setText("no discount"+"final price is "+p);

此外,我用 jCheckBox1.isSelected() 替换了 jCheckBox1.isSelected() == true 部分,因为它已经返回一个 boolean 你不需要再次与布尔值进行比较。

boolean ch1 = jCheckBox1.isSelected();
boolean ch2 = jCheckBox1.isSelected();

if (ch1 && !ch2) {
    // first case
} else if (!ch1 && ch2) {
    // second case
} else if (ch1 && ch2) {
    // third case
}

这段代码包含一个简单的逻辑错误:

if (jCheckBox1.isSelected()==true)
    else if (jCheckBox2.isSelected()==true)

// This condition is not working!!
    else if (jCheckBox1.isSelected()==true && jCheckBox2.isSelected()==true)

如果最后一个条件匹配,则前两个条件已经满足,程序将执行第一个条件中的代码。检查两个复选框是否都被选中必须是第一个条件。否则,除非不满足,否则代码永远不会达到该条件。

并且只需删除此检查 == true 即可大大简化代码,它也只是一个 boolean 值。只需将 if(someBooleanExpression == true) 替换为 if(someBooleanExpression).