如何让我的程序接受超过9位的数字?

时间:2012-10-27 15:31:33

标签: java numbers primes numberformatexception

我目前正在编写一个测试素数的小应用程序。这是基于gui但我有一个问题。我在程序中添加了一些约束,用户只能使用numberformatexception处理程序输入数字,但每当用户输入长度超过9位的数字时,它就不再将其视为数字。有这个问题的解决方案吗?我在下面留下了我的代码。

static void validation() // This is what happens when the "Check" button is clicked
{


    // Retrieve information from the fields and print it out on the Frame
    if (jtfX.getText().trim().length() == 0) // Check if the field is empty
    {
        jlSolution.setText("You have not entered anything yet");

    }

    else // Otherwise...
    {

        try // In general....
        {

            if (Long.parseLong(jtfX.getText()) < 0) // Check if it is a negative value
            {
                                jlSolution.setText("The number you entered is less than zero");
            }
                            else // If it isn't...
            {
                                jlSolution.setText(new Algorithm(Integer.parseInt(jtfX.getText())).check()); // ....then check if this number is prime.
            }
        }

        catch (NumberFormatException nfe) // ... always catch those who refuse to follow simple rules!
        {
            jlSolution.setText("Numerical values only please. " + "You entered: " + jtfX.getText());

        }
    }

}

1 个答案:

答案 0 :(得分:1)

假设类Algorithim是一个自定义编写的类,您可以用BigInteger替换其构造函数中的整数参数以保存更大的值。

您可以像这样更新jlSolution字段:

Algorithm algorithm = new Algorithm(new BigInteger(jtfX.getText()));
jlSolution.setText(algorithm.check());