gpt4 book ai didi

java - while true try catch 嵌套

转载 作者:行者123 更新时间:2023-12-02 00:03:25 24 4
gpt4 key购买 nike

我是 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-catchwhile 循环。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com