【问题标题】:how can i get my program to accept more than 9 digit numbers?我怎样才能让我的程序接受超过 9 位数字?
【发布时间】:2012-10-27 15:31:33
【问题描述】:

我目前正在编写一个测试素数的小应用程序。它是基于 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());

        }
    }

}

【问题讨论】:

  • 更多代码请check() ? ALGORITHM()9位以上的一件事,需要使用BigInteger
  • 如果long 足以满足您的目的,那么这比使用BigInteger 的变化要小得多。

标签: java numbers primes numberformatexception


【解决方案1】:

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

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

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

【讨论】:

  • 感谢分配,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多