Java 长型检测
此代码检测可用于存储从用户处获得的号码的数据类型。如果有多个合适的数据类型,则会列出所有数据类型 但是,代码未能满足正确执行-1000000000000的要求(应该是long)Java 长型检测,java,Java,此代码检测可用于存储从用户处获得的号码的数据类型。如果有多个合适的数据类型,则会列出所有数据类型 但是,代码未能满足正确执行-1000000000000的要求(应该是long) import java.util.Scanner; 导入java.lang.Exception; 导入java.math.biginger; 导入java.util.InputMismatchException; 公共类main { 公共静态void main(字符串参数[]) { 扫描仪控制台=新扫描仪(System.
import java.util.Scanner;
导入java.lang.Exception;
导入java.math.biginger;
导入java.util.InputMismatchException;
公共类main
{
公共静态void main(字符串参数[])
{
扫描仪控制台=新扫描仪(System.in);
int size=console.nextInt();
BigInteger数字[]=新的BigInteger[大小];
BigInteger长=新的BigInteger(“9223372036854775808”);
BigInteger Int=新的BigInteger(“4294967295”);
对于(int i=0;i您的Long
已初始化为2^32-1,这不适合您的示例编号,而值为2^63-1
同时命名变量Long
是一个非常糟糕的主意。它会隐藏作为JDK标准部分的类,并且它违反了JDK,这建议使用类似variableName
的东西考虑使用biginger.bitSize()
来检测所需的位数,这可能要容易得多。不要使用Long作为变量名。谢谢Louis。该函数使代码变得非常简单:)for(int i=0;i 8&&numbers[i].bit length()<16)System.out.printf(“可以安装在:\n*short\n*int\n*Long\n”);else if(numbers[i].bit length()>16&&numbers[i].bitLength()<32)System.out.printf(“可以安装在:\n*int\n*long\n”);else if(数字[i].bitLength()>32&&numbers[i].bitLength()<64)System.out.printf(“可以安装在:\n*long\n”);else if(数字[i].bitLength()>64)System.out.print(“不能安装在任何地方。”;}
你能告诉我为什么不使用Long吗?我对编码有点陌生。我同意@vlad的说法,Long变量的范围是从[-2^63]到[2^63-1],精确地说,范围从-9223372036854775808到9223372036854775807不等。还要尽量避免使用保留关键字命名变量。啊……但我认为case sentivity胜过保留关键字冲突。它不是保留的,但它是一个始终存在且人们都知道的类。当我第一次阅读您的代码时,我正在寻找一个否定()
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.");
}
}
}