如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
使用不同的字符串输入尝试以下代码:
String a = "10";
String a = "10ssda";
String a = null;
String a = "12102";
if(null != a) {
try {
int x = Integer.ParseInt(a.trim());
Integer y = Integer.valueOf(a.trim());
// It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
} catch(NumberFormatException ex) {
// ex.getMessage();
}
}
其他回答
一个方法是parseInt(String)。它返回一个基元int:
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
第二个方法是valueOf(String),它返回一个新的Integer()对象:
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
方法:
整数.parseInt整数.parseInt(s,基数)Integer.parseInt(s,beginIndex,endIndex,基数)整数.parseUnsignedInt整数.parseUnsignedInt(s,基数)Integer.parseUnsignedInt(s,beginIndex,endIndex,基数)整数.valueOf整数.valueOf(s,基数)整数.解码数字Utils.toInt(s)NumberUtils.toInt(s,默认值)
Integer.valueOf生成一个Integer对象,而所有其他方法生成一个基元int。
最后两个方法来自commons-lang3和一篇关于转换的大文章。
这是一个完整的程序,所有条件都是正的和负的,不使用库
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("Not a Number");
}
else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
}
else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
}
else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
}
else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
}
else {
result = beforeDecimal;
}
return result * signBit;
}
}
这可以起作用,
Integer.parseInt(yourString);
手动执行:
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;
}