我是 Java 新手。我希望代码在用户输入的类型错误的地方重复,而不是从头开始。当“输入 b:”或“输入 c:”时,它会返回到开头“输入 a:”。我希望它仅重复,其中用户输入是 a、b、c。提前致谢。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean itsANumber = true;
while (itsANumber)
{
System.out.print("Enter a: ");
try
{
a = Double.parseDouble(sc.nextLine());
System.out.print("Enter b: ");
try
{
b = Double.parseDouble(sc.nextLine());
System.out.print("Enter c: ");
try
{
c = Double.parseDouble(sc.nextLine());
if (a == 0)
{
aZero();
} else
{
aNotZero();
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out.println("That's not a number, please try again!");
}
}
}
最佳答案
引入一个请求号码的方法并调用它三次。在该方法内部,您将拥有带有 try-catch
的 while
循环。
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
double
a = askForDouble(sc, "a"),
b = askForDouble(sc, "b"),
c = askForDouble(sc, "c");
}
static double askForDouble(Scanner sc, String varName) {
for (;/*ever*/;) {
System.out.format("Enter %s: ", varName);
System.out.flush();
try {
return Double.parseDouble(sc.nextLine());
} catch (NumberFormatExcetpion() {
System.out.println("That's not a number, please try again!");
}
}
}
关于java - while true try catch 嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375732/