如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
使用此方法可以避免错误。
String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};
其他回答
对于Java 11,有几种方法可以将int转换为String类型:
1) 整数.parseInt()
String str = "1234";
int result = Integer.parseInt(str);
2) Integer.valueOf()
String str = "1234";
int result = Integer.valueOf(str).intValue();
3) 整数构造函数
String str = "1234";
Integer result = new Integer(str);
4) 整数代码
String str = "1234";
int result = Integer.decode(str);
将字符串转换为int比仅转换数字更复杂。您已经考虑了以下问题:
字符串是否只包含数字0-9?字符串之前或之后的-/+怎么了?这是可能的吗(指会计数字)?MAX_-/MIN_INFINITY怎么了?如果字符串为99999999999999999999,会发生什么?机器可以将此字符串视为int吗?
另一种解决方案是使用Apache Commons的NumberUtils:
int num = NumberUtils.toInt("1234");
Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0。因此,节省了try-catch块。
Apache NumberUtils API 3.4版
您也可以使用此代码,但要注意一些事项。
选项#1:显式处理异常,例如,显示消息对话框,然后停止当前工作流的执行。例如:尝试{字符串字符串值=“1234”;//从字符串到整数int integerValue=Integer.valueOf(stringValue);//或int整数值=整数.ParseInt(字符串值);//现在从整数返回字符串stringValue=String.valueOf(整数值);}catch(NumberFormatException ex){//JOptionPane.showMessageDialog(帧,“无效输入字符串!”);System.out.println(“输入字符串无效!”);回来}选项#2:如果发生异常,执行流可以继续,则重置受影响的变量。例如,在catch块中进行了一些修改catch(NumberFormatException ex){整数值=0;}
使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值。
正如我在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;
}
}