Problem with several && in jFrame

3

I have the following code where I have to control if a food has x ingredients, the thing is that if you meet the ingredients but you select one more, you also consider it good because the code is as follows

if(radioLentejas.isSelected()){
        if(chkChorizo.isSelected() && chkMorcilla.isSelected() && chkGarbanzos.isSelected() && chkZanahoria.isSelected()){
            lblResultado.setText("Correcto");
        }else{
            lblResultado.setText("Equivocado!");
        }
    }

my doubt would be if there is any way to control that only take those elements and none more, because for example if you select those elements but some more would also give it for good

In response, thank you very much to @Jakala, JFrame brings the next event for when the status changes, adding a counter will be enough to then check if the number of checks is correct:

private void chkPimentonItemStateChanged(java.awt.event.ItemEvent evt) {                                             
        if(chkPimenton.isSelected()){
            countChecked++;
        }else if(!chkPimenton.isSelected()){
            countChecked--;
        }
        lblResultado.setText(String.valueOf(countChecked));
    }
    
asked by Alberto Martínez 17.04.2018 в 09:52
source

1 answer

5

Since the "formula" of your recipe is that, one option would be to add the rest of the possible but denied ingredients. For example, if you also had lettuce and cheese, you could do:

if(radioLentejas.isSelected()){
        if(chkChorizo.isSelected() && chkMorcilla.isSelected() && chkGarbanzos.isSelected() && chkZanahoria.isSelected() && !chkLechuga.isSelected() && !chkQueso.isSelected()){
            lblResultado.setText("Correcto");
        }else{
            lblResultado.setText("Equivocado!");
        }
    }

Another way (I'll explain it to you, not to do it exactly in JFrame) is that, somehow you look for the total number of ingredients that you have marked (a count of all the checks). If that count is different from your recipe, it would be that there are more ingredients added and it is wrong:

total_checks = get_checks();  // esto es un ejemplo, hay que modificarlo para JFrame
if(radioLentejas.isSelected()){
        if(chkChorizo.isSelected() && chkMorcilla.isSelected() && chkGarbanzos.isSelected() && chkZanahoria.isSelected() && total_checks == 5){
            lblResultado.setText("Correcto");
        }else{
            lblResultado.setText("Equivocado!");
        }
    }
    
answered by 17.04.2018 / 09:58
source