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,
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))
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.
One possible option would be to create a Map<String, String>
with valid options and pass it to a method with an infinite loop, if the user provides a valid option return it (possibly after performing some action); otherwise display the invalid option message and loop again. Like,
public static String getCommand(Scanner scan, Map<String, String> options) {
while (true) {
String input = scan.nextLine();
if (options.containsKey(input)) {
System.out.println(options.get(input));
return input;
} else {
System.out.printf("%s is not an option!%n", input);
}
}
}
The above could then be called like,
Scanner scan = new Scanner(System.in);
Map<String, String> options = new HashMap<>();
options.put("attack", "You attacked the enemy!");
options.put("defend", "You blocked the enemy!");
String cmd = getCommand(scan, options);
After which cmd
would be one of attack
or defend
. Note that this way you can add as many options
(or type of options
) as you need, and reuse getCommand
.