java quot 转换_如何在Java中轻松地将字符串转换为Integer

在Java中有两种将字符串转换为Integer的方法,

使用Integer.parseInt()到Integer的字符串使用Integer.value eOf()到Integer的字符串

8cea32b3a2101178f80797ebd19f9a0d.png

假设您有一个字符串-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知识,记得关注+关注+关注+转发收藏哦

9553d115a031d55e2fa08c5c1eb8361f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值