java字符串转into,Java将字符串转换为int

我们可以使用Integer.parseInt()方法将String转换为Java中的int。要将String转换为Integer,我们可以使用Integer.valueOf()方法,该方法返回Integer类的实例。

d5ca22a636273a8add33b9d5f1e267b3.png

假设

如果我们必须对包含数字的字符串执行数学运算,则通常使用它。每当我们从TextField或TextArea接收数据时,输入的数据都会作为字符串接收。如果输入的数据为数字格式,则需要将字符串转换为整数。为此,我们使用Integer.parseInt()方法。

签名

parseInt()是Integer类的静态方法。parseInt()方法的签名如下:

public static int parseInt(String s)

将Java字符串转换为int示例:Integer.parseInt()

让我们看一下将Java中的字符串转换为int的简单代码。

public class StringToIntExample1{

public static void main(String args[]){

//Declaring String variable

String s="200";

//Converting String into int using Integer.parseInt()

int i=Integer.parseInt(s);

//Printing value of i

System.out.println(i);

}}

输出:

200

了解字符串串联运算符

public class StringToIntExample{

public static void main(String args[]){

//Declaring String variable

String s="200";

//Converting String into int using Integer.parseInt()

int i=Integer.parseInt(s);

System.out.println(s+100);//200100, because "200"+100, here + is a string concatenation operator

System.out.println(i+100);//300, because 200+100, here + is a binary plus operator

}}

输出:

200100

300

Java String to Integer示例:Integer.valueOf()

Integer.valueOf()方法将String转换为Integer对象。让我们看一下将Java中的String转换为Integer的简单代码。

public class StringToIntegerExample2{

public static void main(String args[]){

String s="200";

Integer i=Integer.valueOf(s);

System.out.println(i);

}}

输出:

300

NumberFormatException大小写

如果字符串文字中没有数字,则调用Integer.parseInt()或Integer.valueOf()方法会引发NumberFormatException。

public class StringToIntegerExample3{

public static void main(String args[]){

String s="hello";

int i=Integer.parseInt(s);

System.out.println(i);

}}

输出:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"

at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.base/java.lang.Integer.parseInt(Integer.java:652)

at java.base/java.lang.Integer.parseInt(Integer.java:770)

at StringToIntegerExample3.main(StringToIntegerExample3.java:4)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值