我一直试图向用户展示一些更好的东西。我正在尝试设置如果他输入了错误的输入,那么他必须重新开始,直到他输入介于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);

关于java - Java用户界面改进,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28654410/

10-13 07:07