I have a boolean array that stores CheckBox values ​​( true or false ). In case all elements of the array are true , I need to perform some operation. So, how to check the array to true in all elements? It is necessary to check for the presence of all true . I tried this:

 boolean[] checked = { true, true, false, true }; for (int z = 0; z < checked.length; z++) { if (checked[z] == false) System.out.println("в массиве есть false!"); } 

It turns out that at every encounter false in the array, the program will show a message. But I need the opposite - showing the message in the absence of false . I add else :

  else System.out.println("в массиве только true!"); 

This way I will get the message to be repeated as many times as true in the array. I need to perform the operation only once, in case there is only true in the array!

UPD A little thought, I wrote this:

 int x = 1; for (int z = 0; z < checked.length; z++) { x = x * ((checked[z] == true) ? 1 : 2); } if (x == 1) { //мои действия } 

I use the ternary operator in each iteration to multiply one by itself (if true ) or by two (if false ). As a result, if the resulting number is one, it means that only true in the array.

  • one
    Cycle Rip on the first encountered false , otherwise true . Are you familiar with the language? - D-side
  • @ D-side, I try, but nothing happens. - Flippy
  • one
    This is a very ordinary situation. What do I think, you did not understand :) Add what you tried. - D-side
  • one
    code that in UPD delete more quickly and does not show anyone. It’s better not to even say that such thoughts were - MrGarison
  • one
    exactly. Check the correct answer if it is :) - MrGarison

2 answers 2

Write method

 public boolean checkArray(boolean[] checked){ for (boolean b : checked) { if (!b) { return false; } } return true; } 

and then just call

 if (checkArray(checked)){ //ваши действия } 
     boolean[] checked= {true, true, false, true}; boolean areAllElementsTrue = true; for(int z = 0; z < checked.length; z++) { if (checked[z] == false) { areAllElementsTrue = false; break; } } if (areAllElementsTrue) { System.out.println("в массиве только true!"); // Выполняйте ваши действия } 
    • thanks, but something is wrong. The operation is performed arbitrarily, in the case of two true of the three, then somehow. The fact is that I “bring” this check when withdrawing / checking the checkbox. I do not know, maybe this is the case. I change the array values ​​along with the checkbox states. - Flippy
    • @ Sergey Grushin I have curly braces for if added to my answer. Now it seems to work. Try it - iramm
    • @ SergeyGrushin It became clear why it didn’t work before. Without these brackets, there was an exit from the loop after checking the first element, and if it was true, then our flag remained true. - iramm
    • Thanks, but I already found a way out) added to the question - Flippy