Java如何存储用户输入的超大数字并与byte/short/int/long类型范围比较
你可以用BigInteger类完成跨范围的数值比较,它自带大小比较方法,且支持任意长度的整数存储,刚好适配你的需求。具体实现逻辑如下:
- 提前将四类整型的上下界转为
BigInteger类型的常量,避免直接使用Math.pow出现的浮点精度误差 - 读取用户输入的字符串直接转为
BigInteger对象,无需担心超出long范围的问题 - 调用
BigInteger的compareTo()方法完成大小判断:如果a.compareTo(b)返回负数,说明a < b;返回0说明a == b;返回正数说明a > b
完整可运行代码如下:
import java.math.BigInteger; import java.util.Scanner; class Zcheck { // 预定义四类整型的边界常量,提前转为BigInteger避免重复创建 private static final BigInteger BYTE_MIN = BigInteger.valueOf(Byte.MIN_VALUE); private static final BigInteger BYTE_MAX = BigInteger.valueOf(Byte.MAX_VALUE); private static final BigInteger SHORT_MIN = BigInteger.valueOf(Short.MIN_VALUE); private static final BigInteger SHORT_MAX = BigInteger.valueOf(Short.MAX_VALUE); private static final BigInteger INT_MIN = BigInteger.valueOf(Integer.MIN_VALUE); private static final BigInteger INT_MAX = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); BigInteger num; // 先校验输入是否为合法整数 try { num = new BigInteger(input); } catch (NumberFormatException e) { System.out.println("输入内容不是合法整数"); return; } // 从小到大判断适配范围,符合最小范围后直接输出所有适配的类型 if (num.compareTo(BYTE_MIN) >= 0 && num.compareTo(BYTE_MAX) <= 0) { System.out.println(input + " can be fitted in:\n* byte\n* short\n* int\n* long"); } else if (num.compareTo(SHORT_MIN) >=0 && num.compareTo(SHORT_MAX) <=0) { System.out.println(input + " can be fitted in:\n* short\n* int\n* long"); } else if (num.compareTo(INT_MIN) >=0 && num.compareTo(INT_MAX) <=0) { System.out.println(input + " can be fitted in:\n* int\n* long"); } else if (num.compareTo(LONG_MIN) >=0 && num.compareTo(LONG_MAX) <=0) { System.out.println(input + " can be fitted in:\n* long"); } else { System.out.println(input + " can't be fitted anywhere."); } } }
该方案使用JDK自带的类型边界常量,比手动计算2的幂次更准确,不会出现浮点精度丢失的问题;所有比较都用BigInteger对象完成,不管输入的数字多大,只要是合法整数都能正常比较,不会出现溢出问题;同时额外增加了非法输入校验,避免用户输入非数字内容时程序崩溃。
内容的提问来源于stack exchange,提问作者Mohit Rajgor
相关产品推荐
相关产品推荐

