Java 如何让我的程序接受超过9位数的数字?
我目前正在编写一个测试素数的小应用程序。它是基于gui的,但我有一个问题。我在程序中添加了一些限制,用户只能使用numberformatexception处理程序输入数字,但每当用户输入的数字超过9位时,它就不再认为它是数字。这个问题有解决办法吗?我在下面留下了我的代码Java 如何让我的程序接受超过9位数的数字?,java,numbers,primes,numberformatexception,Java,Numbers,Primes,Numberformatexception,我目前正在编写一个测试素数的小应用程序。它是基于gui的,但我有一个问题。我在程序中添加了一些限制,用户只能使用numberformatexception处理程序输入数字,但每当用户输入的数字超过9位时,它就不再认为它是数字。这个问题有解决办法吗?我在下面留下了我的代码 static void validation() // This is what happens when the "Check" button is clicked { // Retrieve informatio
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());
}
}
}
static void validation()//单击“检查”按钮时会发生这种情况
{
//从字段中检索信息并在框架上打印出来
if(jtfX.getText().trim().length()==0)//检查该字段是否为空
{
jlSolution.setText(“您还没有输入任何内容”);
}
否则//。。。
{
试试//一般来说。。。。
{
if(Long.parseLong(jtfX.getText())<0)//检查它是否为负值
{
jlSolution.setText(“您输入的数字小于零”);
}
否则//如果不是。。。
{
jlSolution.setText(新算法(Integer.parseInt(jtfX.getText())).check();/…然后检查这个数字是否为素数。
}
}
捕获(NumberFormatException nfe)/…总是捕获那些拒绝遵守简单规则的人!
{
jlSolution.setText(“请仅限数值。”+”您输入了:“+jtfX.getText()”;
}
}
}
假设类Algorithim
是一个自定义编写的类,您可以将其构造函数中的整型参数替换为BigInteger
,以保存较大的值
您将更新jlSolution
字段,如下所示:
Algorithm algorithm = new Algorithm(new BigInteger(jtfX.getText()));
jlSolution.setText(algorithm.check());
更多代码plz,
check()
ALGORITHM()
对于9位以上的数字,您需要使用BigInteger
。如果long
足够满足您的需要,这比使用BigInteger
的更改要小得多。谢谢,非常感谢。