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

前端 未结 3 591
故里飘歌
故里飘歌 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 07:57

    So if you enter defend or attack, it will not ask again, otherwise repeat the process. Try this:

        do{
        String input = scan.nextLine();
        switch( input) {
            case "attack":
               System.out.println( "You attacked the enemy!");
               break;
    
            case "defend":
               System.out.println( "You blocked the enemy!");
               break;
    
            default:
               System.out.println( "This is not an option!");
               // somehow repeat the process until one of the case options are 
               // entered.
        }
    }while(!"attack".equalsIgnoreCase(input) || !"defend".equalsIgnoreCase(input))
    

提交回复
热议问题