Java,检测String是否超出Long类型值边界
Java, detect whether a String beyond Long type value boundary
给出以下 Java
代码:
String columnValue = "188237574385834583453453635";
columnValue =(Long.parseLong(columnValue)>Long.MAX_VALUE?"0":columnValue);
它抛出 java.lang.NumberFormatException
因为输入值超出了 Long
的最大值。但是,是否有一种简单的方法可以在不使用 try
catch
解决方案的情况下检测 'string' 类型中的数字是否超出 Long
的最大值?
不是真的。
唯一简单的部分解决方案是比较字符串的长度,但这并不总是有效。
一种懒惰的方法是使用BigInteger。
BigInteger a = new BigInteger("188237574385834583453453635");
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE);
System.out.println("a > Long.MAX_VALUE is : " + (a.compareTo(b) > 0 ? "true" : "false"));
如果性能很重要,您将不得不测试更多的解决方案。
@SotiriosDelimanolis 的想法也不错:
Extract the source code of parseLong and instead of throwing an
exception, return a boolean.
代码中还有很多throw
,有的是格式的,有的是溢出的,你要选对。
您可以创建一个将 try/catch 和 returns 包装成布尔值的实用方法,例如:
import java.util.*;
import java.lang.*;
import java.io.*;
class TestClass
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(TestClass.isLongString("188237574385834583453453635"));
}
public static boolean isLongString(final String longNumber)
{
boolean isLong = false;
try
{
Long.parseLong(longNumber);
isLong = true;
}
catch(Exception e)
{
// do nothing - return default false
}
return isLong;
}
}
一个非常俗气的方式:
columnValue.length() > ("" + Long.MAX_VALUE).length()
当然,这不包括大于 Long.MAX_VALUE 的值,但位数相同,仅包含位数更多的值。
给出以下 Java
代码:
String columnValue = "188237574385834583453453635";
columnValue =(Long.parseLong(columnValue)>Long.MAX_VALUE?"0":columnValue);
它抛出 java.lang.NumberFormatException
因为输入值超出了 Long
的最大值。但是,是否有一种简单的方法可以在不使用 try
catch
解决方案的情况下检测 'string' 类型中的数字是否超出 Long
的最大值?
不是真的。
唯一简单的部分解决方案是比较字符串的长度,但这并不总是有效。
一种懒惰的方法是使用BigInteger。
BigInteger a = new BigInteger("188237574385834583453453635");
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE);
System.out.println("a > Long.MAX_VALUE is : " + (a.compareTo(b) > 0 ? "true" : "false"));
如果性能很重要,您将不得不测试更多的解决方案。
@SotiriosDelimanolis 的想法也不错:
Extract the source code of parseLong and instead of throwing an exception, return a boolean.
代码中还有很多throw
,有的是格式的,有的是溢出的,你要选对。
您可以创建一个将 try/catch 和 returns 包装成布尔值的实用方法,例如:
import java.util.*;
import java.lang.*;
import java.io.*;
class TestClass
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(TestClass.isLongString("188237574385834583453453635"));
}
public static boolean isLongString(final String longNumber)
{
boolean isLong = false;
try
{
Long.parseLong(longNumber);
isLong = true;
}
catch(Exception e)
{
// do nothing - return default false
}
return isLong;
}
}
一个非常俗气的方式:
columnValue.length() > ("" + Long.MAX_VALUE).length()
当然,这不包括大于 Long.MAX_VALUE 的值,但位数相同,仅包含位数更多的值。