整理:Java面试那些事儿

我们可以使用.()方法将字符串转换为整数。为了将字符串转换为整数,我们可以使用.()方法,它返回类的实例。

字符串转换为整数_串字符整数转换为数字_字符串转为整数的函数

# 场景

通常情况下,如果我们需要对包含数字的字符串进行数学运算字符串转换为整数,就会使用它。每当我们从或接收数据时,接收到的数据是作为字符串。

如果输入的数据是数字格式,我们需要将字符串转换为整数。为此字符串转换为整数,我们使用.()方法。

# 方法签名

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

public static int parseInt(String s)

# Java字符串转换为整数示例:.()

让我们看一个简单的代码示例,将字符串转换为整数

int i=Integer.parseInt("200");

让我们看一个简单的Java字符串转换为整数的示例。

1. //Java Program to demonstrate the conversion of String into int 2. //using Integer.parseInt() method 3. public class StringToIntExample1{ 4. public static void main(String args[]){ 5. //Declaring String variable 6. String s="200"; 7. //Converting String into int using Integer.parseInt() 8. int i=Integer.parseInt(s); 9. //Printing value of i 10. System.out.println(i); 11. }}

输出:

200

理解字符串连接运算符

1. //Java Program to understand the working of string concatenation operator 2. public class StringToIntExample{ 3. public static void main(String args[]){ 4. //Declaring String variable 5. String s="200"; 6. //Converting String into int using Integer.parseInt() 7. int i=Integer.parseInt(s); 8. System.out.println(s+100);//200100, because "200"+100, here + is a string concatenation operator 9. System.out.println(i+100);//300, because 200+100, here + is a binary plus operator 10. }}

输出:

200100300

专属福利

点击领取:Java资料合集!650G!


# Java字符串转换为整数示例:.()

.()方法将字符串转换为对象。让我们看一个简单的代码示例,在Java中将字符串转换为整数

1. //Java Program to demonstrate the conversion of String into Integer 2. //using Integer.valueOf() method 3. public class StringToIntegerExample2{ 4. public static void main(String args[]){ 5. //Declaring a string 6. String s="200"; 7. //converting String into Integer using Integer.valueOf() method 8. Integer i=Integer.valueOf(s); 9. System.out.println(i); 10. }}

输出:

300

# n异常情况

如果字符串字面量中没有数字,则调用.()或.()方法会抛出n异常。

1. //Java Program to demonstrate the case of NumberFormatException 2. public class StringToIntegerExample3{ 3. public static void main(String args[]){ 4. String s="hello"; 5. int i=Integer.parseInt(s); 6. System.out.println(i); 7. }}

输出:

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)

字符串转为整数的函数_串字符整数转换为数字_字符串转换为整数

字符串转为整数的函数_串字符整数转换为数字_字符串转换为整数热门推荐

字符串转为整数的函数_字符串转换为整数_串字符整数转换为数字

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注