如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
公共静态int parseInt(字符串)引发NumberFormatException
可以使用Integer.parseInt()将字符串转换为int。
将字符串“20”转换为原始int:
String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);
输出-20
如果字符串不包含可解析的整数,则将引发NumberFormatException:
String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);
公共静态Integer valueOf(字符串)引发NumberFormatException
您可以使用Integer.valueOf()。在这种情况下,它将返回一个Integer对象。
String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);
输出-20
工具书类https://docs.oracle.com/en/
其他回答
这可以起作用,
Integer.parseInt(yourString);
import java.util.*;
public class strToint {
public static void main(String[] args) {
String str = "123";
byte barr[] = str.getBytes();
System.out.println(Arrays.toString(barr));
int result = 0;
for(int i = 0; i < barr.length; i++) {
//System.out.print(barr[i]+" ");
int ii = barr[i];
char a = (char) ii;
int no = Character.getNumericValue(a);
result = result * 10 + no;
System.out.println(result);
}
System.out.println("result:"+result);
}
}
将String转换为Int的一些方法如下:
可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);
嗯,需要考虑的一个非常重要的点是Integer解析器抛出了Javadoc中所述的NumberFormatException。
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
在尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。
也可以从删除所有非数字字符开始,然后解析整数:
String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);
但请注意,这只适用于非负数。