我希望这段代码继续执行,直到输入可接受的答案(即1,2,3,4),但我不知道如何做到这一点。谢谢。另外,如果有任何其他方法可以简化此操作,也会有所帮助。
import java.util.Scanner;
public class NewMain {
public static void main(String[] args) {
String input;
Scanner keyboard = new Scanner(System.in);
System.out.println("Your choice\n[1]Up \n[2]Down \n[3]Left \n[4]Right");
input = keyboard.nextLine();
if(input.equals("1")) {
System.out.println("You are going up!!!");
}
else {
if(input.equals("2")){
System.out.println("You are going down!!!");
}
else {
if(input.equals("3")) {
System.out.println("You are going left!!!");
}
else {
if(input.equals("4")) {
System.out.println("You are going right!!!");
}
else{}
}
}
}
}
}
最佳答案
尝试使用开关盒 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
您的案例:
while(flag == false){
switch (imput) {
case "1":
System.out.println("You are going up!!!"); flag=true;
break;
case "2":
System.out.println("You are going down!!!"); flag = true;
break;
case "3":
System.out.println("You are going left!!!"); flag = true;
break;
case "4": System.out.println("You are going right!!!"); flag = true;
break;
}
}
您可以输入可选条件默认:
关于java - 我怎样才能让这段代码继续下去,直到选择正确的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20576500/