public class StrToInt {
public static final String Min_number = "-9223372036854775808";
public static final String Max_number = "9223372036854775807";
public static Long strToNumber(String s) {
long number = 0;
// 需要先判断是否为空,再判断是否为空串 否则会报空指针异常
if (s == null || s.equals("")) {
System.out.println("传入的字符串为空或空指针!");
return (long) 0;
}
boolean isNum = s.matches("-{0,1}[0-9]+");
if (!isNum) {
System.out.println("输入的数字不合法!");
return (long) 0;
}
if (s.startsWith("-")) {
if (s.length() > Min_number.length()) {
System.out.println("该字符串超过数字的下届");
return (long) 0;
}
if (s.length() == Min_number.length() && s.compareTo(Min_number) > 0) {
System.out.println("该字符串超过数字的下届");
return (long) 0;
}
} else {
if (s.length() > Max_number.length()) {
System.out.println("该字符串超过数字的上届");
return (long) 0;
}
if (s.length() == Max_number.length() && s.compareTo(Max_number) > 0) {
System.out.println("该字符串超过数字的上届");
return (long) 0;
}
}
number = Long.parseLong(s);
return number;
}
public static void main(String[] args) {
System.out.println(strToNumber("-666"));
System.out.println(strToNumber("666"));
System.out.println(strToNumber(""));
System.out.println(strToNumber(null));
System.out.println(strToNumber("1a9"));
System.out.println(strToNumber("-9223372036854775809"));
System.out.println(strToNumber("9223372036854775808"));
}
}