参考链接:
源码:
/** * Parses the string argument as a signed decimal integer. The * characters in the string must all be decimal digits, except * that the first character may be an ASCII minus sign {@code '-'} * ({@code '\u005Cu002D'}) to indicate a negative value or an * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to * indicate a positive value. The resulting integer value is * returned, exactly as if the argument and the radix 10 were * given as arguments to the {@link #parseInt(java.lang.String, * int)} method. * * @param s a {@code String} containing the {@code int} * representation to be parsed * @return the integer value represented by the argument in decimal. * @exception NumberFormatException if the string does not contain a * parsable integer. */ public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); }
分析:底层是通过parseInt(s,10)进行转换的,当输入的字符串中的内容不是数字时,会抛出NumberFormatException异常。
举例:
(1)正常时
String number = "12345"; // Integer.parseInt():返回原始整数 int i = Integer.parseInt(number); System.out.println("i = " + i);// i = 12345
(2)不正常时
String number1 = "12345A"; int i1 = Integer.parseInt(number1); System.out.println("i1 = " + i1);
输出结果:
Exception in thread "main" java.lang.NumberFormatException: For input string: "12345A" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at string.StringToNumberTest.testStringToIntOrInteger(StringToNumberTest.java:29) at string.StringToNumberTest.main(StringToNumberTest.java:12)
为此需要加try...catch...:
String number1 = "12345A"; try{ int i1 = Integer.parseInt(number1); System.out.println("i1 = " + i1); }catch (NumberFormatException e){ System.out.println("Unable to convert input string (" + number1 + ") to int"); }
输出结果:
Unable to convert input string (12345A) to int
源码:
/** * Returns an {@code Integer} object holding the * value of the specified {@code String}. The argument is * interpreted as representing a signed decimal integer, exactly * as if the argument were given to the {@link * #parseInt(java.lang.String)} method. The result is an * {@code Integer} object that represents the integer value * specified by the string. * *In other words, this method returns an {@code Integer} * object equal to the value of: * *
* {@code new Integer(Integer.parseInt(s))} ** * @param s the string to be parsed. * @return an {@code Integer} object holding the value * represented by the string argument. * @exception NumberFormatException if the string cannot be parsed * as an integer. */ public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }
分析:底层也是通过parseInt(s,10)进行转换的,当输入的字符串中的内容不是数字时,会抛出NumberFormatException异常。
举例:
(1)正常时
String number = "12345"; // Integer.valueOf():返回一个Integer对象 Integer integer = Integer.valueOf(number); System.out.println("integer = " + integer);// integer = 12345
(2)不正常时
String number1 = "12345A"; Integer integer1 = Integer.valueOf(number1); System.out.println("integer1 = " + integer1);
输出结果:
Exception in thread "main" java.lang.NumberFormatException: For input string: "12345A" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.valueOf(Integer.java:766) at string.StringToNumberTest.testStringToIntOrInteger(StringToNumberTest.java:40) at string.StringToNumberTest.main(StringToNumberTest.java:12)
为此需要加try...catch...:
String number1 = "12345A"; try { Integer integer1 = Integer.valueOf(number1); System.out.println("integer1 = " + integer1); }catch (NumberFormatException e){ System.out.println("Unable to convert input string (" + number1 + ") to int"); }
输出结果:
Unable to convert input string (12345A) to int
测试代码:
package string; /** * @ClassName StringToNumberTest * @Description TODO * @Author Jiangnan Cui * @Date 2022/11/15 20:45 * @Version 1.0 */ public class StringToNumberTest { public static void main(String[] args) { // String number = "12345";// 输出12345 // String number = "12345A";// 抛异常 // String number = "-12345";// 输出12345 String number = "012345";// 输出12345 if (isDigit(number)) { System.out.println(Integer.parseInt(number)); } else { System.out.println("Please provide a valid digit [0-9]"); } } /** * @MethodName isDigit * @Description 判断输入字符串内容是否是数字,检查输入,但是代价很高 * @param: input * @return: boolean * @Author Jiangnan Cui * @Date 23:09 2022/11/16 */ public static boolean isDigit(String input) { // null or length < 0, return false. if (input == null || input.length() < 0) return false; // empty, return false input = input.trim();// 从当前字符串中删除所有前导和尾随空白字符 if ("".equals(input)) return false; // negative number in string if (input.startsWith("-")) { // cut the first char return input.substring(1).matches("[0-9]*"); } else { // positive number, good, just check return input.matches("[0-9]*"); } } }
使用前要先导入依赖:
com.google.guava guava 15.0
测试代码:
package test; import com.google.common.primitives.Ints; import java.util.Optional; public class TestInts { public static void main(String[] args) { Integer integer = Optional.ofNullable("123").map(Ints::tryParse).orElse(0); System.out.println("integer = " + integer);// integer = 123 } }
测试代码:
package string; import java.util.Optional; /** * @ClassName StringToNumberTest2 * @Description TODO * @Author Jiangnan Cui * @Date 2022/11/18 7:51 * @Version 1.0 */ public class StringToNumberTest2 { public static void main(String[] args) { String number = "12345";// 输出12345 // String number = "12345A";// 报错 // String number = "-12345";// 输出12345 // String number = "012345";// 输出12345 Optionalresult = Optional.ofNullable(number) .filter(StringToNumberTest::isDigit) .map(Integer::parseInt);// 先判断是否为空,再过滤出是数字的,最后进行提取 if (!result.isPresent()) { System.out.println("Please provide a valid digit [0-9]"); } else { System.out.println(result.get()); } } }
补充:
对于Integer类型,可以通过.intValue()方法转化为int类型。
其余String转基本数据类型方法应该类似,如果有差别,后续再补充。
参考链接:
源码:
/** * Returns the string representation of the {@code int} argument. ** The representation is exactly the one returned by the * {@code Integer.toString} method of one argument. * * @param i an {@code int}. * @return a string representation of the {@code int} argument. * @see java.lang.Integer#toString(int, int) */ @NotNull @Contract(pure=true) public static String valueOf(int i) { return Integer.toString(i); } /** * Returns the string representation of the {@code Object} argument. * * @param obj an {@code Object}. * @return if the argument is {@code null}, then a string equal to * {@code "null"}; otherwise, the value of * {@code obj.toString()} is returned. * @see java.lang.Object#toString() */ public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
测试:
int num = 12345; String s = String.valueOf(num); System.out.println("s = " + s);// s = 12345 Integer num1 = 12345; String s1 = String.valueOf(num1); System.out.println("s1 = " + s1);// s1 = 12345 Integer num2 = null; String s2 = String.valueOf(num2); System.out.println("s2 = " + s2);// s2 = null
注意:valueOf()括号中的内容不能为空,否则会报空指针异常。
源码:
/** * Returns a {@code String} object representing this * {@code Integer}'s value. The value is converted to signed * decimal representation and returned as a string, exactly as if * the integer value were given as an argument to the {@link * java.lang.Integer#toString(int)} method. * * @return a string representation of the value of this object in * base 10. */ public String toString() { return toString(value); }
测试:
Integer num1 = 12345; String s3 = num1.toString(); System.out.println("s3 = " + s3);// s3 = 12345
测试:
Integer num1 = 12345; Integer num2 = null; String s4 = num1 + ""; System.out.println("s4 = " + s4);// s4 = 12345 String s5 = num2 + ""; System.out.println("s5 = " + s5);// s5 = null
注意:第三种相对第一二种方法耗时较大。
参考链接:http://ych0108.iteye.com/blog/2174134
举例:
String.format("%010d", 25); // 25为int型
0代表前面要补的字符
10代表字符串长度
d表示参数为整数类型
测试代码:
// 将25保存成00025 int num = 25; // 方法一:5前面不指定内容时,去除num位数后前面补空格 String format = String.format("%5d", num); System.out.println("format = " + format);// format = 25 // 将空格替换为0 String str = format.replace(" ", "0"); System.out.println("str = " + str);// str = 00025 // 方法二:5前面指定内容0时,去除num位数后前面补0 String format1 = String.format("%05d", num); System.out.println("format1 = " + format1);// format1 = 00025
注意:方法二只需要在数字前加0就可以进行填充,比方法一更加方便。