我想知道如果我在'输入'中的输入无效,我怎么能跳过我的尝试再次尝试。例如,我输入'o'作为我的选择。它应显示“无效输入”,它应显示菜单部分(再次跳过尝试)。请帮帮我。
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
答案 0 :(得分:0)
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
boolean inputWasValid = false;
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
inputWasValid = true;
System.out.println("invalid input");
break;
}
if (inputWasValid) {
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
@Kevin说,你可以试试这个。答案 1 :(得分:0)
我的理解是你想要这样的东西:
...
Scanner in = new Scanner(System.in);
String yn = null;
boolean retry;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
retry = true;
switch (input) {
...
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
// might want to do check & loop here to see if user enters just Y or N
if(retry && yn.equalsIgnoreCase("N")) retry = false;
} while (retry);
有了这个,你会得到以下结果:
I
再试一次Y
将再次循环播放I
再试一次N
将终止循环P
再次尝试Y
将再次循环播放(显示无效输入,但允许用户选择继续)P
再次尝试N
将终止循环(显示无效输入,用户决定不继续)