【发布时间】:2019-05-07 12:47:36
【问题描述】:
我有这段代码计算指数示例 3⁴ = 81.0,代码询问用户他想输入多少个数字和指数,以及当用户输入数字和指数时,他输入了一个无效的输入字母,代码将捕获 java.util.InputMismatchException 并停止。有没有代码可以返回输入的数字和指数重新输入?
我已经尝试过布尔值,但它不起作用,我正在搜索这个东西,但没有人工作。
try {
String[] unicode = {"\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"};
System.out.print("Enter how many Numbers and Exponent you want to enter: ");
int userNum = new Scanner(System.in).nextInt();
ArrayList<Integer> num = new ArrayList<>();
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < userNum; i++) {
System.out.print("Enter a Number: ");
int userNumber = new Scanner(System.in).nextInt();
num.add(userNumber);
System.out.print("Enter the exponent: ");
int userExponent = new Scanner(System.in).nextInt();
nums.add(userExponent);
}
for (int i = 0; i < userNum; i++) {
double answer = num.get(i);
for (int x = 0; x < nums.get(i) - 1; x++) {
answer *= num.get(i);
}
System.out.print(num.get(i));
for (int x = 0; x < String.valueOf(nums.get(i)).length(); x++) {
char g = String.valueOf(nums.get(i)).charAt(x);
String h = String.valueOf(g);
System.out.print(unicode[Integer.parseInt(h)]);
}
System.out.println(" = " + answer);
}
} catch (InputMismatchException exception) {
System.out.println(exception+" Invalid Input. Numbers Only.");
}
}
我对此的期望是,当用户输入无效输入时,程序将捕获 java.util.InputMismatchException 并打印它并返回输入再次输入
例如。
输入编号:12
输入指数:asd
java.util.InputMismatchException
输入指数:123
【问题讨论】:
-
您可能希望
try/catch在循环中,而不是相反。在这种情况下,当循环中出现异常时,将退出循环并控制到 catch 块。 -
@ernest_k 所说的。也许还可以在循环中提取一些方法以使其更具可读性/可维护性。由于 for 循环中的 try 和 catch 子句往往会变得混乱