如何将String转换为int?

"1234"  →  1234

当前回答

您可以有自己的实现,例如:

public class NumericStringToInt {

    public static void main(String[] args) {
        String str = "123459";

        int num = stringToNumber(str);
        System.out.println("Number of " + str + " is: " + num);
    }

    private static int stringToNumber(String str) {

        int num = 0;
        int i = 0;
        while (i < str.length()) {
            char ch = str.charAt(i);
            if (ch < 48 || ch > 57)
                throw new NumberFormatException("" + ch);
            num = num * 10 + Character.getNumericValue(ch);
            i++;
        }
        return num;
    }
}

其他回答

您也可以使用此代码,但要注意一些事项。

选项#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;}

使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值。

一个方法是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和一篇关于转换的大文章。

您只需尝试以下操作:

使用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){};