public void getAnswer() {
System.out.println("Give an answer");
String answer = reader.nextLine();
switch(answer) {
case "a":
ans = 10;
break;
case "b":
ans = 20;
break;
case "c":
ans = 30;
break;
default:
System.out.println("Please give a correct answer!");
getAnswer();
}
System.out.println(a);
}
static Scanner scanner = new Scanner(System.in);
public static void getAnswer() {
System.out.println("Give an answer");
String answer = scanner.nextLine();
int ans = -1;
switch (answer) {
case "a":
ans = 10;
break;
case "b":
ans = 20;
break;
case "c":
ans = 30;
break;
default:
System.out.println("Please give a correct answer!");
getAnswer();
return;
}
System.out.println(ans);
}
,输出:
Give an answer d Please give a correct answer! Give an answer d Please give a correct answer! Give an answer a 10