samedi 24 décembre 2016

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

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, let's say I take an input from the user with the Scanner class. Imagine that Scanner is imported and everything is set.

Scanner scan = new Scanner();
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.
}

I could put this inside a while loop and when a case option is entered I could exit out of the while loop, but that just seems too much code when I have plenty of switch/if statements that both require a solid input in order to process the rest of the code. Is there a way to do this more efficiently in Java?

Aucun commentaire:

Enregistrer un commentaire