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

时间:2015-10-02 11:28:42

标签: java swing if-statement jcheckbox

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

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);

3 个答案:

答案 0 :(得分:2)

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

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)替换为{{1}}。

答案 1 :(得分:1)

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

    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() == true替换为jCheckBox1.isSelected(),因为它已经返回boolean,您无需再次使用布尔值进行比较。

答案 2 :(得分:1)

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
}