如何将 Java 字符串转换为int
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-string-to-int
在 Java 中,可以使用 Integer.pareseInt() 方法和 Integer.valueOf() 方法将字符串转换为 int 值。
例如,当我们接收到字符串形式的用户输入,并且要求在执行任何数学运算之前将其转换为整数时。这可以通过 parseInt() 方法完成。
使用Integer.parseInt()
方法转换
parseInt()
方法是整数类的一部分。这是一个静态方法,用于将字符串转换为整数。这里,一个string
值被转换成int
值。
例 1:
public class StudyTonight
{
public static void main(String args[])
{
String s = "454"; //String Declaration
System.out.println("String value "+s);
int i = Integer.parseInt(s);
System.out.println("Integer value "+i);
}
}
字符串值 454 整数值 454
使用Integer.valueOf()
方法转换
valueOf()
方法是整数类的一部分。此方法用于将String
转换为integer
。请看下面的例子。
例 2:
如果提供的字符串不包含有效的数字,则valueOf()
方法返回异常。
public class StudyTonight
{
public static void main(String args[])
{
try
{
String s1 = "500"; //String declaration
Integer i1 = Integer.valueOf(s1); // Integer.valueOf() method converts a String into Integer
System.out.println(i1);
String s2 = "mohit"; //NumberFormatException
Integer i2 = Integer.valueOf(s2);
System.out.println(i2);
}
catch(Exception e)
{
System.out.println("Invalid input");
}
}
}
500 无效输入
例 3:
转换也可以手动完成,如示例所示:
class StudyTonight
{
public static int strToInt(String str)
{
int i = 0;
int num = 0;
boolean isNeg = false;
// Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-')
{
isNeg = true;
i = 1;
}
// Process each character of the string;
while( i < str.length())
{
num *= 10;
num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
public static void main(String[] args)
{
String s = "45734";
int i = strToInt(s);
System.out.println("Int value is : "+i);
}
}
Int 值为:45734