有什么方法可以实现复选框的 switch case 吗?
示例:我有4个复选框,如果我选择了2个复选框,如何触发案例到我想要的输出?
double exam = 0.0, assign = 0.0, quiz = 0.0, ct = 0.0;
if (examchkbox.isSelected()) {
exam = Double.parseDouble(examtextfield.getText());
}
if(ctchkbox.isSelected()) {
ct = Double.parseDouble(cttextfield.getText());
}
if(quizchkbox.isSelected()) {
quiz = Double.parseDouble(quiztextfield.getText());
}
if(asschkbox.isSelected()) {
assign = Double.parseDouble(asstextfield.getText());
}
if (!(exam + ct + quiz + assign == 100)) {
markerrorlbl.setText("Total marks must be 100");
}
else {
// implementation of code here
}
这是设计 View 。
假设我勾选了考试和类测试,我只想选择文本字段中的值并使用 switch case 存储分数。这可能吗?
这就是我想要的东西,但我不知道如何用 Checkbox 实现。
switch(x)
{
case 1 : A = new exam(marks) ;total+=marks; break;
case 2 : A = new test(marks) ;total+=marks; break;
case 3 : A = new quiz(marks) ;total+=marks; break;
case 4 : A = new assignment(marks) ;total+=marks;break;
}
最佳答案
为什么要使用 switch 而不是代码中已有的 if 语句?
由于您可以彼此独立地选择四个复选框,因此开关
在这里并不是最佳解决方案。您有四个复选框,因此有 2^4 = 16 种可能的“检查模式”:
int pattern = (cb1.isSelected() ? 0b0001 : 0)
| (cb2.isSelected() ? 0b0010 : 0)
| (cb3.isSelected() ? 0b0100 : 0)
| (cb4.isSelected() ? 0b1000 : 0);
switch (pattern) {
case 0b0001:
// code for when only checkbox 1 is checked
break;
...
case 0b0011:
// code for when checkbox 1 and checkbox 2 are checked
break;
...
case 0b1011:
// code for when only checkbox 1, 2 and 4 are checked
break;
...
}
如果使用开关,则需要 16 个案例。相比之下,您只需要 4 个 if 语句:
if (checkbox 1 is checked) {
// code for when checkbox 1 is checked
}
if (checkbox 2 is checked) {
// code for when checkbox 2 is checked
}
...
请注意,这是 4 个独立的 if 语句,其中没有 else if
。
关于java - 复选框 switch case 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27017355/