在Java中有两种将字符串转换为Integer的方法,
使用Integer.parseInt()到Integer的字符串使用Integer.value eOf()到Integer的字符串
假设您有一个字符串-strTest-包含一个数值。
String strTest = “100”;
尝试执行一些算术操作,比如除以4-这会立即显示一个编译错误。
class StrConvert{ public static void main(String []args){ String strTest = "100"; System.out.println("Using String:" + (strTest/4)); }}
产出:
/StrConvert.java:4: error: bad operand types for binary operator '/' System.out.println("Using String:" + (strTest/4));
因此,在对字符串执行peform数值操作之前,需要将其转换为int。
示例1:使用Integer.parseInt()将字符串转换为Integer
parseInt方法的语法如下:
int = Integer.parseInt();
传递字符串变量作为参数。
这将Java字符串转换为JavaInteger,并将其存储到指定的整数变量中。检查下面的代码片段-
class StrConvert{ public static void main(String []args){ String strTest = "100"; int iTest = Integer.parseInt(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int: " + (iTest/4)); }}
产出:
Actual String:100Converted to Int:100Arithmetic Operation on Int: 25
示例2:使用Integer.value eOf()将字符串转换为Integer
还使用Integer.value eOf()方法将字符串转换为Java中的Integer。
下面的代码示例演示了使用Integer.value eOf()方法的过程:
public class StrConvert{ public static void main(String []args){ String strTest = "100"; //Convert the String to Integer using Integer.valueOf int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int:" + (iTest/4)); }}
产出:
Actual String:100Converted to Int:100Arithmetic Operation on Int:25
NumberFormatException异常
如果试图解析无效的数字字符串,则引发NumberFormatException。例如,字符串‘Guru 99’不能转换为Integer。
例子:
public class StrConvert{ public static void main(String []args){ String strTest = "Guru99"; int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); }}
上面的例子给出了输出中的以下异常:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"
,想了解更多JAVA知识,记得关注+关注+关注+转发收藏哦