Java用户界面改进



我一直在尝试更好地向用户展示这一点。我正在尝试设置,如果他输入了错误的数字,那么他必须重新开始,直到他输入了设置在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));
}
}

我建议使用Integer.parseInt(...)并检查NumberFormatException

以下边做边工作:

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);

如果用户输入的值大于9000,则不会抛出任何错误,因此您的"Thats too much"消息将永远不会显示,要显示该消息,您必须执行如下检查:

if(a >= 9000 || b >= 9000){
   System.out.println("Thats too much");
}

相关内容

  • 没有找到相关文章

最新更新