所以我创建一个简短的测试只是为了看看我的朋友的证据是否正确是没有正整数,当写两次(即10-> 1010)是一个完美的正方形。
package checker;
import static java.lang.Math.*;
public class Checker {
public static void main(String[] args) {
for(int i=10001; i<1000000; i++) {
String repeat = i + "" + i;
int x = Integer.valueOf(repeat);
double root = Math.sqrt(x);
if (root == Math.floor(root) && !Double.isInfinite(root)) {
System.out.println("When " + i + " is repeated and the root is taken of it, the result, " + x
+ " IS a perfect square.");
}
}
}
};
当我运行它时,我收到错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "2147521475"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.valueOf(Integer.java:766)
at checker.Checker.main(Checker.java:11)
我对Java很新,所以我不太了解。感谢帮助。感谢。
答案 0 :(得分:0)
Java中int
可以表示的最大值是2,147,483,647。您尝试解析的值(2,147,521,475)太大而无法表示为int
。
NumberFormatException
是Java的说法,字符串“2147521475”无法解析为整数。
如果您使用long
而不是int
(即将int x = Integer.valueOf
更改为long x = Long.valueOf
),那么您应该没问题。
答案 1 :(得分:0)
int
的最大值为2 31 -1或2147483647.您的号码2147521475超过此值(并且是您的程序将尝试的第一个此类号码)。
作为临时的止损,您可以使用long
,long x = Long.valueOf(repeat)
,其最大值为2 63 -1,使用BigInteger
。
然而,这仍然会最终破坏(虽然经过很长一段时间取决于所使用的计算机和算法)。您可以使用{{1}}来处理该案例。
答案 2 :(得分:0)
Int数据类型是32位带符号的二进制补码整数。 最低值为 - 2,147,483,648。( - 2 ^ 31) 最大值为2,147,483,647(含)。(2 ^ 31 -1)
使用long
public static void main(String[] args) {
for(long i=10001; i<1000000; i++) {
String repeat = i + "" + i;
long x = Long.valueOf(repeat);
double root = Math.sqrt(x);
if (root == Math.floor(root) && !Double.isInfinite(root)) {
System.out.println("When " + i + " is repeated and the root is taken of it, the result, " + x
+ " IS a perfect square.");
}
}
}