如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
您只需尝试以下操作:
使用Integer.parseInt(your_string);将字符串转换为int使用Double.parseDouble(your_string);将字符串转换为double
实例
String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955
String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
其他回答
您只需尝试以下操作:
使用Integer.parseInt(your_string);将字符串转换为int使用Double.parseDouble(your_string);将字符串转换为double
实例
String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955
String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
使用此方法可以避免错误。
String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};
嗯,需要考虑的一个非常重要的点是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.
}
在尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。
实现这一点的两种主要方法是使用Integer类的方法valueOf()和方法parseInt()。
假设给你一个这样的字符串
String numberInString = "999";
然后可以使用
int numberInInteger = Integer.parseInt(numberInString);
或者,您可以使用
int numberInInteger = Integer.valueOf(numberInString);
但这里的问题是,Integer.valueOf()方法在Integer类中有以下实现:
public static Integer valueOf(String var0, int var1) throws NumberFormatException {
return parseInt(var0, var1);
}
如您所见,Integer.valueOf()在内部调用Integer.parseInt()本身。此外,parseInt()返回int,valueOf()则返回Integer
正如我在GitHub上写的:
public class StringToInteger {
public static void main(String[] args) {
assert parseInt("123") == Integer.parseInt("123");
assert parseInt("-123") == Integer.parseInt("-123");
assert parseInt("0123") == Integer.parseInt("0123");
assert parseInt("+123") == Integer.parseInt("+123");
}
/**
* Parse a string to integer
*
* @param s the string
* @return the integer value represented by the argument in decimal.
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
*/
public static int parseInt(String s) {
if (s == null) {
throw new NumberFormatException("null");
}
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("s=" + s);
}
number = number * 10 + s.charAt(i) - '0';
}
return isNegative ? -number : number;
}
}