Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch with if, else if, else, and loops inside case

Tags:

java

For the purpose of my question I've only included case 1, but the other cases are the same. Let's say value is currently 1, we go to case 1 and our for loop goes through the array to see if each element matches with the whatever_value variable. In this case if it does, we declare the value variable to be equal to 2, and we break out of the loop. The problem is that when i highlight the other break(in eclipse), it says that the breaks are attached to the for statement as well, but i only wanted the for statement to be attached to the if statement, not the else if statements as well. I thought because there are no brackets for the for statement that it would only loop for the if statement but eclipse says otherwise(else if also loops from 0 to the length of the array).

  switch (value) {
  case 1:
     for (int i = 0; i < something_in_the_array.length; i++)
        if (whatever_value == (something_in_the_array[i])) {
           value = 2;
           break;
        } else if (whatever_value == 2) {
           value = 3;
           break;
        } else if (whatever_value == 3) {
           value = 4;
           break;
        }
     break;
  case 2:

  // code continues....
like image 925
BubbleTree Avatar asked Dec 04 '22 14:12

BubbleTree


1 Answers

Your problem..... I think is that your for loop is encompassing all of the if, else if stuff - which acts like one statement, like hoang nguyen pointed out.

Change to this. Note the brackets that denote the code block on which the for loop operates and the change of the first else if to if.

switch(value){

    case 1:
        for(int i=0; i<something_in_the_array.length;i++) {
            if(whatever_value==(something_in_the_array[i])) {
                value=2;
                break;
             }
        }

        if(whatever_value==2) {
            value=3;
            break;
        }
        else if(whatever_value==3) {
            value=4;
            break;
        }
        break;


    case 2:

code continues....
like image 194
eboix Avatar answered Dec 30 '22 14:12

eboix