复选框开关盒的实现 [英] Implementation of switch case for check box
问题描述
有什么方法可以实现复选框的 switch case?
Is there any way to implement switch case for checkbox?
例如:我有 4 个复选框,如果我选择了 2 个复选框,如何将 case 触发到我想要的输出?
Example: I have 4 checkboxes, if I selected 2 checkboxes, how to trigger the case to the output I want?
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
}
这是设计视图.
假设我勾选了考试和课堂测试,我只想在文本字段中选择值并使用 switch case 存储标记.这可能吗?
Let say I ticked Exam and Class Test, I just want to select the value in the text field and store the marks by using switch case. Is that possible?
这就是我想要的,但我不知道如何使用 Checkbox 实现.
This is the thing about I want but I've no idea how to implement with 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 语句?
Why do you want to use a switch instead of the if statements you already have in your code?
因为您可以相互独立地选择四个复选框,所以 switch
在这里不是最好的解决方案.您有四个复选框,因此有 2^4 = 16 种可能的检查模式":
Since you can select the four checkboxes independently from each other, a switch
is not the best solution here. You have four checkboxes, so there are 2^4 = 16 possible "check patterns":
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 you use a switch, you would need 16 cases. In contrast, you only need 4 if statements:
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
.
Note that these are 4 independent if statements, no else if
s there.
这篇关于复选框开关盒的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!