-2

I wanted to implement a game with levels and after winning the current level, the user can solve another one. I did it by for each loop using enum data. If you have a another way of solving this problem, please share with me. Program already changes levels after right decision from user, but I want to implement that if user provides a wrong answer, it exits from main loop. I tried to solve it with the break operator, but it doesn't work. If you have another solution to this problem, please share with me.

static void levelchanger() {
    Levelinfo[] types = Levelinfo.values();
    for (Levelinfo arr : types) {
        while (arr.moves != 0 && arr.display != arr.goal) {
            System.out.println("It is " + arr + " level. You have: " + arr.moves + " moves. Goal: " + arr.goal);
            System.out.println("Step: 1) " + arr.gnumbers[0] + " 2) " + arr.gnumbers[1]);
            Scanner in = new Scanner(System.in);
            int action = in.nextInt();
            switch (action) {
            case 1:
                arr.display += arr.gnumbers[0];
                System.out.println("Result: " + arr.display);
                break;
            case 2:
                arr.display += arr.gnumbers[1];
                System.out.println("Result: " + arr.display);
                break;
            }
            arr.moves--;
            if (arr.moves == 0 && arr.display != arr.goal) {
                System.out.println("You don't have more moves!");
                break;
            } else if (arr.display == arr.goal) {
                System.out.println("Alright! Next level");
            }
        }
    }
}
Jeppe
  • 1,830
  • 3
  • 24
  • 33
jazyshy
  • 49
  • 1
  • 1
  • 8

2 Answers2

1

add tag to the loop

a: for (;;)
   {
     while()
     {
      if(condition)
        break a;// at your condition  write like this
     }

   }
0

The break statement will only break out of the current loop.

You can either change your break to a return if there is nothing else you want to do after the for, or restructure your code to make use of smaller methods, so that you avoid so much nesting within one method.

You can also add a boolean variable which is set to false, and checked in the for loop but will probably make the code dirtier.

jbx
  • 21,365
  • 18
  • 90
  • 144