-2

i am preparung for exams in programming java I. In this exercise I am supposed to run the code by myself and say what comes out. This code is given by the professor of my course. I didn't create this code.

Following is the code:

public class SS13Aufg2 {

    public static void main(String[] args) {

        int a = 1;
        int b = 2;
        while (a < 6) {
            a = a + 2;
            switch (a%3) {
                case 0 : b = a-b;
                case 1 : b = a*b;
            }
        }
    }

}

What I am not able to unterstand, is already in the first time of run through. a = 3 --> a%3 is 0 and case 0 comes out. But after that the program runs case 1 as well. Why? it is not the case.

kellerprogger
  • 109
  • 2
  • 2
  • 12

1 Answers1

1

You need to use break here. And having a default case is ideal.

switch (a%3) {
    case 0 : b = a-b;
        break;
    case 1 : b = a*b;
        break;
    default:System.out.println("Invalid");          
        break;
}

Read more.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115