我正在编写一个简单的程序,该程序从Scanner对象接收整数输入,确定它是否是回文,然后返回布尔值。
对于大多数数字,它都可以正常工作。但是,在此代码段中:
private static void programRunner() {
System.out.print("Insert your number:");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int testNumber = in.nextInt();
boolean result = palindromeTester(testNumber);
System.out.println(result);
programRunner();
} else {
System.exit(0);
}
}
我添加了“ System.exit(0)”表达式,以使用户可以通过有意键入任何非整数值来轻松终止程序。问题是,当提供“相当大”的整数(例如“ 1234567654321”)时,代码将启动System.exit(0),这意味着无法将其识别为整数?
我相信问题出在hasNextInt方法的“默认半径”,它可能会限制它识别的整数值的大小。(该程序最多可以运行9位整数),但我不确定。还是递归有问题?
因为int
Java中的an是32位,并且只能保存2^31 - 1
(2147483647)作为最大值(另请参见Integer.MAX_VALUE)。
大于该值的值不是int
,但是long
(大于的值除外Long.MAX_VALUE
,在这种情况下,您需要将值设为BigInteger
。)
请参见Integer.MAX_VALUE,Long.MAX_VALUE,Scanner.nextInteger(),Scanner.nextLong(),Scanner.nextBigInteger()和BigInteger。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句