2

Sorry, I am new to Java! I have a question regarding using multiple if statements in a loop like a while. I will make clear my question through an example. if condition 1 is wrong, how can we switch to the while again( without processing other conditions)?

 public static void main(String[] args) {
                // TODO Auto-generated method stub

            while(){
            if(condition1){

            if(condition2){

            if(condition3){

                   }    

            }

roeygol
  • 4,908
  • 9
  • 51
  • 88
Amir Em
  • 37
  • 5
  • 1
    Have a look at things like continue, or break. First goes back to top of loop. Last exits look. You can also nest loops and append a tag to continue or break. See here https://stackoverflow.com/a/26431031/495157 – JGFMK Feb 23 '20 at 09:46

2 Answers2

3

Use keyword

continue;

to skip processing and proceed with next loop iteration.

The Keyword

break;

would completely jump out of the loop.

Better design in your case would be nesting the if statements:

if (condition1) {
    if (condition2) {
    ...
    }
}

So the next condition is only checked when the further one is true.

If you do so, you don't have to struggle with continue; statements.

You are also able to combine multiple conditions in one if statement:

if (condition1 && condition2) {
    // do something
}

In this case code is only executed when all conditions are true. If the first condition is false, the second condition will not even be checked because false && true would be false.

otto
  • 190
  • 1
  • 7
2
while(){
  if(condition1) {
      if(condition2) {
          if(condition3) {
          }
      }
  }
}
Anton Straka
  • 139
  • 2