How to repeat an if or switch statement if something out of option is entered?

前端 未结 3 563
故里飘歌
故里飘歌 2021-01-14 07:44

This will mostly get duplicated but I sincerely don\'t know how to search this question since it is too long and complicated. Sorry in advance!

Back to the problem,

3条回答
  •  星月不相逢
    2021-01-14 08:03

    Scanner scan = new Scanner(System.in);
    loop:
    while (true) {
        String input = scan.nextLine();
        switch (input) {
            case "attack":
                System.out.println("You attacked the enemy!");
                break loop;
    
            case "defend":
                System.out.println("You blocked the enemy!");
                break loop;
    
            default:
                System.out.println("This is not an option!");
                break;
        }
    }
    

    while (true) makes an infinite loop as you may know. In the switch statement, if the input is attack or defend, we break out of the loop. If it is neither of those, we only break out of the switch statement.

    The while loop is marked with the loop: label. This is so that we can tell it to break loop; to break out of the loop. On the other hand break only breaks out of the switch statement.

提交回复
热议问题