简体   繁体   English

"如何检测一个数字是否大于 Long.MAX 值"

[英]How to detect if a number is greater than Long.MAX value

My application will get number as string from end user.我的应用程序将从最终用户那里获得数字作为字符串。 If the number is not numeric, i have to throw error message by saying that to provide number.如果数字不是数字,我必须通过说提供数字来抛出错误消息。 This i can fix by using NumberFormatException.我可以通过使用 NumberFormatException 来解决这个问题。 Another scenario is, user entered greater than Long.MAX value.另一种情况是,用户输入的值大于 Long.MAX 值。 How i can check this case and give error message to the user to enter smaller number than Long.MAX value?我如何检查这种情况并向用户提供错误消息以输入小于 Long.MAX 值的数字? I should not use any third party or open source lib to fix this issue.我不应该使用任何第三方或开源库来解决这个问题。 Even if they are providing solution, How they are resolving it?即使他们提供解决方案,他们是如何解决的?

"

Use BigInteger to parse user input and compare the result with Long.MAX_VALUE使用BigInteger解析用户输入并将结果与​​ Long.MAX_VALUE 进行比较

String userInput = ...;
BigInteger bigInt = new BigInteger(userInput);
if(bigInt.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
    throw new Exception(userInput + ": value is too large");
}

If the entered number is greater than Long.MAX value, then what will you do next.如果输入的数字大于Long.MAX值,那么您接下来要做什么。 It will cause an error as you don't know where to store it.它会导致错误,因为您不知道将其存储在哪里。

Better way is to check at the time of user input is in range or not.更好的方法是在用户输入时检查是否在范围内。 If it is greater than Long.MAX , store it in BigInteger如果它大于Long.MAX ,则将其存储在BigInteger

Use BigInteger and the longValueExact() method, and catch exceptions:使用BigIntegerlongValueExact()方法,并捕获异常:

public static void main(String[] args) {
    test("123");
    test("9223372036854775807");  // Long.MAX_VALUE
    test("-9223372036854775808"); // Long.MIN_VALUE
    test("9223372036854775808");  // Long.MAX_VALUE + 1
    test("-9223372036854775809"); // Long.MIN_VALUE - 1
    test("abc");
}
private static void test(String input) {
    long longVal;
    try {
        longVal = new BigInteger(input).longValueExact();
    } catch (NumberFormatException e) {
        System.out.println("Value is not a valid integer number: " + input);
        return;
    } catch (ArithmeticException e) {
        System.out.println("Value exceeds range of long: " + input);
        return;
    }
    System.out.println("Got valid long value: " + longVal);
}

OUTPUT输出

Got valid long value: 123
Got valid long value: 9223372036854775807
Got valid long value: -9223372036854775808
Value exceeds range of long: 9223372036854775808
Value exceeds range of long: -9223372036854775809
Value is not a valid integer number: abc

您可以使用 Long.MAX_VALUE 访问最大值并检查用户在 if 条件中输入的值。

Here is another solution without using an extra class other than Java core这是另一个不使用Java核心以外的额外类的解决方案

public static void main(String[] args) {
    System.out.println(isLargerThanLONGMAXVALUE("9223372036854775807"));      // false
    System.out.println(isLargerThanLONGMAXVALUE("9223372036854775806"));      // false
    System.out.println(isLargerThanLONGMAXVALUE("9223372036854775808"));      // true
    System.out.println(isLargerThanLONGMAXVALUE("645459223372036854775807")); // true
    System.out.println(isLargerThanLONGMAXVALUE("922"));                      // false
}

public static boolean isLargerThanLONGMAXVALUE (String number) {
    String longMax = String.valueOf(Long.MAX_VALUE);
    if (number.length() > longMax.length()) return true;
    if (number.length() < longMax.length()) return false;
    long a, b = 0;
    for (int i = 1 ; i < number.length() ; i++){
        a = Long.parseLong(number.substring(0, i));
        b = Long.parseLong(longMax.substring(0, i));
        if (a > b) return true;
    }
    if (Integer.parseInt(number.substring(number.length()-1, number.length())) > 
        Integer.parseInt(longMax.substring(number.length()-1, number.length())))
        return true;
    return false;
}

Treating the string as a BigInteger and doing the comparison is the best way.将字符串视为BigInteger并进行比较是最好的方法。 But here's another just to show that there's usually more than one way to accomplish something:但这里有另一个只是为了表明通常有不止一种方法可以完成某事:

public boolean isInRange(String number) {
    String maxValue = Long.toString(Long.MAX_VALUE);
    number = number.replaceFirst("^0+", "");  // remove leading zeroes
    return number.length() < maxValue.length() ||
           (number.length() == maxValue.length() &&
            number.compareTo(maxValue) <= 0);
}

This assumes that number is composed entirely of digits (no negative sign).这假设number完全由数字组成(没有负号)。

try{
  val n = input.toLong()
}catch(e: Exception){
  // invalid Long
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM