Search code examples
javaswitch-statementjcheckbox

Implementation of switch case for check box


Is there any way to implement switch case for checkbox?

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
                }

Design View This is the design view.

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?

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

Solution

  • Why do you want to use a switch instead of the if statements you already have in your code?

    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;
        ...
    }
    

    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 
    }
    ...    
    

    Note that these are 4 independent if statements, no else ifs there.