Java 我需要跳过代码中我不需要的一部分';我不知道怎么做
我想知道如果我在“输入”中的输入无效,如何跳过重试部分。例如,我输入“o”作为我的选择。它应该显示“无效输入”,并且应该显示菜单部分(跳过重试)。请帮帮我Java 我需要跳过代码中我不需要的一部分';我不知道怎么做,java,Java,我想知道如果我在“输入”中的输入无效,如何跳过重试部分。例如,我输入“o”作为我的选择。它应该显示“无效输入”,并且应该显示菜单部分(跳过重试)。请帮帮我 public class Menu { public static void MainMenu() { Part1 call1 = new Part1(); Part2 call2 = new Part2(); Part3 call3 = new Part3(); Pa
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"));
}
}
}
正如@Kevin所说,你可以试试这个。我的理解是你想要这样的东西:
...
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
if(inputWasValid){…}
?我想我想说的是,如果我输入了无效的输入,它不会给用户重试的选项。它将显示--家庭作业--部分,用户将输入另一部分choice@Ms.Smoak以下问题都不值得接受吗?
...
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);