我一直试图向用户提供更好一点。我试图设置如果他输入错误的输入然后他必须重新开始直到他输入正确的数字设置在0和9000之间。它也是一个乘法迭代和递归。但是我不确定为什么我设置的消息在他出错时没有显示。知道为什么和改进想法,得到任何代码示例?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Multiplication {
public static int multIterative(int a, int b) {
int result = 0;
while (b > 0) {
result += a;
b--;
}
return result;
}
public static int multRecursive(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return a + multRecursive(a, b - 1);
}
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner userInput = new Scanner(System.in);
do {
System.out.print("Please enter first Integer: ");
System.out.print("Please enter second Integer: ");
try {
a = userInput.nextInt();
b = userInput.nextInt();
} catch (InputMismatchException e) {
System.out.println("Must enter an integer!");
userInput.next();
} catch (StackOverflowError e) {
System.out.println("Thats too much");
userInput.next();
}
} while (a >= 9000 || b >= 9000);
System.out.println("The Multiplication Iteration would be: "
+ multIterative(a, b));
System.out.println("The Multiplication Recursion would be: "
+ multRecursive(a, b));
}
}
答案 0 :(得分:0)
如果用户输入的值大于9000
,则不会抛出任何错误,因此您的"Thats too much"
消息将永远不会显示,以显示该消息,您必须执行以下检查:
if(a >= 9000 || b >= 9000){
System.out.println("Thats too much");
}
答案 1 :(得分:0)
我建议改为使用Integer.parseInt(...)
并检查NumberFormatException
。
跟随do-while有效:
do
try {
System.out.print("Please enter first Integer: ");
a = Integer.parseInt(userInput.next());
System.out.print("Please enter second Integer: ");
b = Integer.parseInt(userInput.next());
if (a >= 9000 || b >= 9000)
throw new StackOverflowError();
break;
} catch (NumberFormatException e) {
System.out.println("Must enter an integer!");
} catch (StackOverflowError e) {
System.out.println("Thats too much");
}
while (true);