I have a quick question. I want to make my code shorter and I'm wondering whether I can put in some way below checkboxes into loop. The sense of this part of code is to enable "Find" button in case when at least one of checkbox is selected. Thank you in advance for every tip.
if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
|| checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
|| checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
|| checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
|| checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
|| checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
|| checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
|| checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
button.setEnabled(true);
Of course you can :
boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
found = checkBoxes[i].isSelected();
}
if (found) {
button.setEnabled(true);
}
or you can avoid the boolean
variable and break out of the loop when you find the first selected checkbox :
for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
// for loop
if (checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Why not to use stream
?
if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
button.setEnabled(true);
}
As you have an array of course you can use a loop.
Here is a version with an enhanced loop :
for (Checkbox checkBox : checkBoxes){
if (checkBox.isSelected()){
button.setEnabled(true);
break;
}
}
try this:
for(int i=0; i < checkBoxes.length; i++) {
if(checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Boolean j = false;
for (byte i = 0; i <= 21)
if (checkBoxes[i].isSelected() == true) {
j = true;
break;
if (j == true) {
//your code
}
you van use this code it is so easy
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.