java - 对长类型检测的疑问

标签 java

此代码检测您可以使用哪种数据类型来存储从用户处获取的号码。如果有多种合适的数据类型,则会列出所有内容。

但是,代码无法满足正确执行-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/

相关文章:

java - java类函数太多,如何拆分成多个文件

java - Libgdx 角色运行动画未显示

java - 在上传的图像文件之上绘图

java - 将正则表达式中的字符串拆分为 - 作为一个单词

java - 数组集合 : Optimized code

java - 无法解析 "onRequestPermissionsResult"

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 一种获取多种类型的方法

java - 限制 log4j2 模式中的最大消息大小

java - 在 Angular + Spring Security 应用程序中找不到错误