JAVA 中 string 和 int 互相转化
引言
在JAVA编程中,字符串和整数是两种最基本的数据类型。字符串是由字符序列组成的,而整数是由数字组成的。在编写JAVA程序时,经常需要将字符串转换为整数或整数转换为字符串。这是一项基础而重要的任务,因此本文将介绍JAVA中如何进行字符串和整数之间的相互转换。
字符串转整数
将字符串转换为整数是一项非常基本的操作,JAVA提供了两种方法来实现这一目标。下面将分别介绍这两种方法。
使用 Integer 类的 parseInt() 方法
该方法是将字符串转换为整数的最常用方法之一。它的语法如下:
int intValue = Integer.parseInt(String strValue);
其中,strValue 是要转换的字符串,intValue 是转换后的整数。下面是一个使用该方法的示例:
String strValue = "123"; int intValue = Integer.parseInt(strValue); System.out.println(intValue);
运行结果为:
123
需要注意的是,如果要转换的字符串不是数字字符串,将会抛出 NumberFormatException 异常。因此,在使用该方法时应该对异常进行处理,如下所示:
try {
String strValue = "abc";
int intValue = Integer.parseInt(strValue);
System.out.println(intValue);
} catch (NumberFormatException e) {
System.out.println("字符串无法转换为整数!");
}
运行结果为:
字符串无法转换为整数!
使用 Integer 类的 valueOf() 方法
该方法也可以将字符串转换为整数,其语法如下:
Integer intValue = Integer.valueOf(String strValue);
与 parseInt() 方法不同的是,valueOf() 方法返回的是一个 Integer 对象,而不是一个 int 类型的整数。下面是一个使用该方法的示例:
String strValue = "123"; Integer intValue = Integer.valueOf(strValue); System.out.println(intValue);
运行结果为:
123
需要注意的是,如果要转换的字符串不是数字字符串,将会抛出 NumberFormatException 异常。因此,在使用该方法时应该对异常进行处理,如下所示:
try {
String strValue = "abc";
Integer intValue = Integer.valueOf(strValue);
System.out.println(intValue);
} catch (NumberFormatException e) {
System.out.println("字符串无法转换为整数!");
}
运行结果为:
字符串无法转换为整数!
整数转字符串
将整数转换为字符串也是一项非常基本的操作,JAVA提供了两种方法来实现这一目标。下面将分别介绍这两种方法。
使用 String 类的 valueOf() 方法
该方法是将整数转换为字符串的最常用方法之一。它的语法如下:
String strValue = String.valueOf(int intValue);
其中,intValue 是要转换的整数,strValue 是转换后的字符串。下面是一个使用该方法的示例:
int intValue = 123; String strValue = String.valueOf(intValue); System.out.println(strValue);
运行结果为:
123
使用 Integer 类的 toString() 方法
该方法也可以将整数转换为字符串,其语法如下:
String strValue = Integer.toString(int intValue);
与 valueOf() 方法不同的是,toString() 方法返回的也是一个字符串。下面是一个使用该方法的示例:
int intValue = 123; String strValue = Integer.toString(intValue); System.out.println(strValue);
运行结果为:
123
结论
在JAVA编程中,字符串和整数是两种最基本的数据类型。在处理字符串和整数之间的相互转换时,我们可以使用 Integer 类的 parseInt() 方法、valueOf() 方法,或者使用 String 类的 valueOf() 方法、Integer 类的 toString() 方法。这些方法都是非常基础而重要的,掌握它们对于JAVA编程入门者来说至关重要。
本文来源:词雅网
本文地址:https://www.ciyawang.com/ov03mx.html
本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。
词雅网