此代码检测您可以使用哪种数据类型来存储从用户处获取的号码。如果有多种合适的数据类型,则会列出所有内容。
但是,代码无法满足正确执行-100000000000000(应该属于长)
import java.util.Scanner;
import java.lang.Exception;
import java.math.BigInteger;
import java.util.InputMismatchException;
public class Mainn
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
int size = console.nextInt();
BigInteger numbers[] = new BigInteger[size];
BigInteger Long = new BigInteger("9223372036854775808");
BigInteger Int = new BigInteger("4294967295");
for(int i=0;i<size;i++)
{
numbers[i]=console.nextBigInteger();
}
for(int i=0;i<size;i++)
{
System.out.print(numbers[i]);
if(numbers[i].compareTo(BigInteger.valueOf(-65536)) > 0 && numbers[i].compareTo(BigInteger.valueOf(65535))<0)
System.out.printf(" can be fitted in:\n* short\n* int\n* long\n");
else if(numbers[i].compareTo(Int.negate()) > 0 && numbers[i].compareTo(Int.subtract(BigInteger.valueOf(1)))<0)
System.out.printf(" can be fitted in:\n* int\n* long\n");
else if(numbers[i].compareTo(Long.negate()) > 0 && numbers[i].compareTo(Long.subtract(BigInteger.valueOf(1)))<0)
System.out.printf(" can be fitted in:\n* long\n");
else
System.out.print(" can't be fitted anywhere.");
}
}
}
最佳答案
您的 Long
被初始化为 2^32-1,这不适合您的示例数字,而 Long.MAX_VALUE
值为 2^63-1。
同时命名变量Long
是一个非常糟糕的主意。它遮蔽了类 Long
这是 JDK 的标准部分,它违反了 conventions ,建议使用类似 variableName
.
关于java - 对长类型检测的疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730399/