gpt4 book ai didi

java - 当用户输入的号码不存在时如何捕获 Switch 语句中的错误

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

我正在尝试对我的程序进行错误证明,该程序基本上用作迷你计算器。但我不知道如何编写一个“Catch”语句来检测用户何时输入不存在的案例编号,在我的例子中是任何负数或> 4

        System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");


Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();


int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;

case 2:
subtractingMethod();
n=2;
break;

case 3:
multiplyingMethod();
n=2;
break;

case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}

} while(n==1);
operacijai.close();

} ```

最佳答案

为什么要抛出不必要的异常?我建议您在 switch 中放置一个 default 案例,并包含所需的错误消息。另外,将输入部分移动到循环内,以便它继续接受输入。

我还建议您使用 nextLine() 而不是 nextInt()。检查Scanner is skipping nextLine() after using next() or nextFoo()?了解更多信息。

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = 0, n = 1;
boolean valid;
do {
do {
valid = true;
try {
operacija = Integer.parseInt(operacijai.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter an integer only.");
valid = false;
}
} while (!valid);
switch (operacija) {
case 1:
System.out.println("addingMethod()");
n = 2;
break;

case 2:
System.out.println("subtractingMethod()");
n = 2;
break;

case 3:
System.out.println("multiplyingMethod()");
n = 2;
break;

case 4:
System.out.println("dividingMethod()");
n = 2;
break;
default:
System.out.println("Invalid input");
}
} while (n == 1);
}
}

示例运行:

Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
5
Invalid input

另一个示例运行:

Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()

关于java - 当用户输入的号码不存在时如何捕获 Switch 语句中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61047815/

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