繁体   English   中英

如何将 String 转换为 Java 中的 int?

[英]How do I convert a String to an int in Java?

如何将String转换为int

"1234"  →  1234
String myString = "1234";
int foo = Integer.parseInt(myString);

如果您查看Java 文档,您会注意到“捕获”是此函数可以抛出NumberFormatException ,您可以处理:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
   foo = 0;
}

(此处理默认将格式错误的数字设置为0 ,但如果您愿意,您可以执行其他操作。)

或者,您可以使用 Guava 库中的Ints方法,该方法与 Java 8 的Optional结合使用,是一种将字符串转换为 int 的强大而简洁的方法:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)

例如,这里有两种方法:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

这些方法之间存在细微差别:

  • valueOf返回一个新的或缓存的java.lang.Integer实例
  • parseInt返回原始int

所有情况都相同: Short.valueOf / parseShortLong.valueOf / parseLong等。

嗯,需要考虑的一个非常重要的一点是 Integer 解析器会抛出 NumberFormatException ,如Javadoc中所述。

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.
}

在尝试从拆分参数获取整数值或动态解析某些内容时,处理此异常很重要。

手动执行:

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;
}

另一种解决方案是使用Apache Commons 的NumberUtils:

int num = NumberUtils.toInt("1234");

Apache 实用程序很好,因为如果字符串是无效的数字格式,则总是返回 0。 因此为您节省了 try catch 块。

Apache NumberUtils API 版本 3.4

目前我正在为大学做作业,我不能使用某些表达式,例如上面的那些,通过查看 ASCII 表,我设法做到了。 这是一个复杂得多的代码,但它可以帮助像我一样受到限制的其他人。

首先要做的是接收输入,在这种情况下是一串数字; 我将它称为String number ,在这种情况下,我将使用数字 12 来举例说明它,因此String number = "12";

另一个限制是我不能使用重复循环,因此也不能使用for循环(本来是完美的)。 这限制了我们一点,但话又说回来,这就是目标。 由于我只需要两位数(取最后两位数),一个简单的charAt解决了它:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length() - 2);
 int lastdigitASCII = number.charAt(number.length() - 1);

有了代码,我们只需要查看表格,并进行必要的调整:

 double semilastdigit = semilastdigitASCII - 48;  // A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

现在,为什么要加倍? 好吧,因为一个非常“奇怪”的步骤。 目前我们有两个双精度数,1 和 2,但我们需要将其变成 12,我们无法进行任何数学运算。

我们以2/10 = 0.2 (因此为什么要加倍)的方式将后者(lastdigit)除以 10,如下所示:

 lastdigit = lastdigit / 10;

这只是在玩数字。 我们把最后一位数字变成了小数。 但是现在,看看会发生什么:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

无需过多研究数学,我们只是将数字的位数隔离开来。 你看,因为我们只考虑 0-9,除以 10 的倍数就像创建一个“盒子”来存储它(回想一下你一年级的老师向你解释什么是单位和一百)。 所以:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

你去吧。 考虑到以下限制,您将数字字符串(在本例中为两位数)转换为由这两位数组成的整数:

  • 没有重复循环
  • 没有“魔术”表达式,例如 parseInt

Integer.decode

您还可以使用public static Integer decode(String nm) throws NumberFormatException

它也适用于基数 8 和 16:

// base 10
Integer.parseInt("12");     // 12 - int
Integer.valueOf("12");      // 12 - Integer
Integer.decode("12");       // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8);  // 10 - int
Integer.valueOf("12", 8);   // 10 - Integer
Integer.decode("012");      // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16);  // 18 - int
Integer.valueOf("12",16);   // 18 - Integer
Integer.decode("#12");      // 18 - Integer
Integer.decode("0x12");     // 18 - Integer
Integer.decode("0X12");     // 18 - Integer
// base 2
Integer.parseInt("11",2);   // 3 - int
Integer.valueOf("11",2);    // 3 - Integer

如果你想得到int而不是Integer你可以使用:

  1. 拆箱:

     int val = Integer.decode("12");
  2. intValue()

     Integer.decode("12").intValue();

这样做的方法:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

Integer.valueOf 生成一个 Integer 对象,所有其他方法生成一个原始 int。

最后两种方法来自commons-lang3和一篇关于转换here的大文章。

每当给定的 String 不包含 Integer 的可能性很小时,您就必须处理这种特殊情况。 遗憾的是,标准 Java 方法Integer::parseIntInteger::valueOf抛出NumberFormatException来表示这种特殊情况。 因此,您必须使用异常来进行流控制,这通常被认为是糟糕的编码风格。

在我看来,这种特殊情况应该通过返回一个空的Optional<Integer>来处理。 由于 Java 不提供这样的方法,因此我使用以下包装器:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

示例用法:

// prints "12"
System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
// prints "-1"
System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
// prints "invalid"
System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));

虽然这仍然在内部使用异常进行流控制,但使用代码变得非常干净。 此外,您可以清楚地区分-1被解析为有效值的情况和无法解析无效字符串的情况。

将字符串转换为 int 比仅转换数字更复杂。 您考虑过以下问题:

  • 字符串是否仅包含数字0-9
  • 字符串之前或之后的-/+是怎么回事? 这可能吗(指会计数字)?
  • MAX_-/MIN_INFINITY 怎么了? 如果字符串是 999999999999999999999 会发生什么? 机器可以将此字符串视为 int 吗?

使用Integer.parseInt(yourString)

记住以下几点:

Integer.parseInt("1"); // 行

Integer.parseInt("-1"); // 行

Integer.parseInt("+1"); // 行

Integer.parseInt(" 1"); // 异常(空格)

Integer.parseInt("2147483648"); // 异常(整数限制为最大值2,147,483,647)

Integer.parseInt("1.1"); // 异常( .或任何不允许的)

Integer.parseInt(""); // 异常(不是 0 什么的)

只有一种类型的异常: NumberFormatException

我们可以使用Integer包装类的parseInt(String str)方法将 String 值转换为整数值。

例如:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

Integer类还提供了valueOf(String str)方法:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

我们还可以使用 NumberUtils Utility ClasstoInt(String strValue)进行转换:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);

我有一个解决方案,但我不知道它的效果如何。 但它运作良好,我认为你可以改进它。 另一方面,我使用JUnit进行了几次测试,这些测试步骤正确。 我附上了功能和测试:

static public Integer str2Int(String str) {
    Integer result = null;
    if (null == str || 0 == str.length()) {
        return null;
    }
    try {
        result = Integer.parseInt(str);
    } 
    catch (NumberFormatException e) {
        String negativeMode = "";
        if(str.indexOf('-') != -1)
            negativeMode = "-";
        str = str.replaceAll("-", "" );
        if (str.indexOf('.') != -1) {
            str = str.substring(0, str.indexOf('.'));
            if (str.length() == 0) {
                return (Integer)0;
            }
        }
        String strNum = str.replaceAll("[^\\d]", "" );
        if (0 == strNum.length()) {
            return null;
        }
        result = Integer.parseInt(negativeMode + strNum);
    }
    return result;
}

使用 JUnit 进行测试:

@Test
public void testStr2Int() {
    assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    assertEquals("Not
     is numeric", null, Helper.str2Int("czv.,xcvsa"));
    /**
     * Dynamic test
     */
    for(Integer num = 0; num < 1000; num++) {
        for(int spaces = 1; spaces < 6; spaces++) {
            String numStr = String.format("%0"+spaces+"d", num);
            Integer numNeg = num * -1;
            assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
            assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
        }
    }
}

您还可以从删除所有非数字字符开始,然后解析整数:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);

但请注意,这只适用于非负数。

Google GuavatryParse(String) ,如果无法解析字符串,则返回null ,例如:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

除了以前的答案,我想添加几个功能。 这些是您使用它们时的结果:

public static void main(String[] args) {
  System.out.println(parseIntOrDefault("123", 0)); // 123
  System.out.println(parseIntOrDefault("aaa", 0)); // 0
  System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
  System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}

执行:

public static int parseIntOrDefault(String value, int defaultValue) {
  int result = defaultValue;
  try {
    result = Integer.parseInt(value);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex, endIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

如前所述,Apache Commons 的NumberUtils可以做到这一点。 如果无法将字符串转换为 int,则返回0

您还可以定义自己的默认值:

NumberUtils.toInt(String str, int defaultValue)

例子:

NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1)     = 1
NumberUtils.toInt(null, 5)   = 5
NumberUtils.toInt("Hi", 6)   = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty("  32 ", 1)) = 32;

您也可以使用此代码,但要采取一些预防措施。

  • 选项 #1:显式处理异常,例如,显示消息对话框,然后停止当前工作流的执行。 例如:

     try { String stringValue = "1234"; // From String to Integer int integerValue = Integer.valueOf(stringValue); // Or int integerValue = Integer.ParseInt(stringValue); // Now from integer to back into string stringValue = String.valueOf(integerValue); } catch (NumberFormatException ex) { //JOptionPane.showMessageDialog(frame, "Invalid input string!"); System.out.println("Invalid input string!"); return; }
  • 选项 #2:如果发生异常时执行流程可以继续,则重置受影响的变量。 例如,在 catch 块中进行一些修改

    catch (NumberFormatException ex) { integerValue = 0; }

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

您可以使用new Scanner("1244").nextInt() 或者询问是否存在 int: new Scanner("1244").hasNextInt()

在编程竞赛中,您确信数字始终是有效整数,然后您可以编写自己的方法来解析输入。 这将跳过所有与验证相关的代码(因为您不需要任何代码)并且效率更高。

  1. 对于有效的正整数:

     private static int parseInt(String str) { int i, n = 0; for (i = 0; i < str.length(); i++) { n *= 10; n += str.charAt(i) - 48; } return n; }
  2. 对于正整数和负整数:

     private static int parseInt(String str) { int i=0, n=0, sign=1; if (str.charAt(0) == '-') { i = 1; sign = -1; } for(; i<str.length(); i++) { n* = 10; n += str.charAt(i) - 48; } return sign*n; }
  3. 如果您希望在这些数字之前或之后有空格,请确保在进一步处理之前执行str = str.trim()

对于普通字符串,您可以使用:

int number = Integer.parseInt("1234");

对于字符串生成器和字符串缓冲区,您可以使用:

Integer.parseInt(myBuilderOrBuffer.toString());

你可以试试这个:

  • 使用Integer.parseInt(your_string); String转换为int
  • 使用Double.parseDouble(your_string); 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 作为参数的 Integer 构造函数。

所以,这里是:

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - 整数(字符串)

当然,构造函数将返回类型Integer ,并且拆箱操作将值转换为int


注意 1:重要的是要提到:此构造函数调用parseInt方法。

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}

注 2:已弃用@Deprecated(since="9") - JavaDoc

int foo = Integer.parseInt("1234");

确保字符串中没有非数字数据。

开始了

String str = "1234";
int number = Integer.parseInt(str);
print number; // 1234

使用 Integer.parseInt() 并将其放在try...catch块中以处理任何错误,以防输入非数字字符,例如,

private void ConvertToInt(){
    String string = txtString.getText();
    try{
        int integerValue=Integer.parseInt(string);
        System.out.println(integerValue);
    }
    catch(Exception e){
       JOptionPane.showMessageDialog(
         "Error converting string to integer\n" + e.toString,
         "Error",
         JOptionPane.ERROR_MESSAGE);
    }
 }

它可以通过七种方式完成:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

String number = "999";
  1. Ints.tryParse

    int 结果 = Ints.tryParse(number);

  2. NumberUtils.createInteger

    整数结果 = NumberUtils.createInteger(number);

  3. NumberUtils.toInt

    int 结果 = NumberUtils.toInt(number);

  4. Integer.valueOf

    整数结果 = Integer.valueOf(number);

  5. Integer.parseInt

    int 结果 = Integer.parseInt(number);

  6. Integer.decode

    int 结果 = Integer.decode(number);

  7. Integer.parseUnsignedInt

    int 结果 = Integer.parseUnsignedInt(number);

一种方法是 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);

这是一个完整的程序,所有条件都是正面和负面的,无需使用库

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;
    }
}

您可以使用以下任何一种:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

执行此操作的两种主要方法是使用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()返回一个intvalueOf()返回一个Integer

public static int parseInt(String s)throws NumberFormatException

您可以使用Integer.parseInt()将 String 转换为 int。

将字符串“20”转换为原始整数:

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);

public static Integer valueOf(String s)throws 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/

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输入试试这个代码:

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();
    }
}

使用 Java Integer 类的parseInt方法将字符串转换为整数。 parseInt方法是将String 转换为int,如果字符串不能转换为int 类型,则抛出NumberFormatException

忽略它可以抛出的异常,使用这个:

int i = Integer.parseInt(myString);

如果变量myString所代表的 String 是“1234”, “200”, “1”,等有效整数“1234”, “200”, “1”,则将其转换为 Java int。 如果由于任何原因失败,更改可能会抛出NumberFormatException ,因此代码应该更长一点来说明这一点。

例如Java Stringint转换方法,控制一个可能的NumberFormatException

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // Use this if you want to test the exception below
    String s = "1234";

    try
    {
      // The String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // Print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

如果更改尝试失败 - 在这种情况下,如果您可以尝试将 Java String 测试转换为 int - Integer parseInt进程将抛出NumberFormatException ,您必须在 try/catch 块中处理该NumberFormatException

正如我在 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;
    }
}

通过使用此方法,您可以避免错误。

String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};

有多种方法可以将字符串 int 值转换为 Integer 数据类型值。 您需要处理字符串值问题的 NumberFormatException。

  1. Integer.parseInt

     foo = Integer.parseInt(myString);
  2. 整数值

     foo = Integer.valueOf(myString);
  3. 使用 Java 8 可选 API

     foo = Optional.of(myString).map(Integer::parseInt).get();

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

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;
    }
}

这可以工作,

Integer.parseInt(yourString);

我编写了这个快速方法来将输入的字符串解析为 int 或 long。 它比当前的 JDK 11 Integer.parseInt 或 Long.parseLong 更快。 虽然,你只要求 int,但我也包括了长解析器。 下面的代码解析器要求解析器的方法必须很小才能快速运行。 替代版本位于测试代码下方。 替代版本非常快,并且不依赖于类的大小。

此类检查溢出,您可以自定义代码以适应您的需要。 使用我的方法,空字符串将产生 0,但这是有意的。 您可以更改它以适应您的情况或按原样使用。

这只是类中需要 parseInt 和 parseLong 的部分。 请注意,这仅处理基数为 10 的数字。

int 解析器的测试代码在下面的代码下方。

/*
 * Copyright 2019 Khang Hoang Nguyen
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * @author: Khang Hoang Nguyen - kevin@fai.host.
 **/
final class faiNumber{
    private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
                                           10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
                                           1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
                                          };

    private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
                                          100000, 1000000, 10000000, 100000000, 1000000000
                                        };

    /**
     * parseLong(String str) parse a String into Long.
     * All errors throw by this method is NumberFormatException.
     * Better errors can be made to tailor to each use case.
     **/
    public static long parseLong(final String str) {
        final int length = str.length();
        if (length == 0)
            return 0L;

        char c1 = str.charAt(0);
        int start;

        if (c1 == '-' || c1 == '+') {
            if (length == 1)
                throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
            start = 1;
        } else {
            start = 0;
        }

        /*
         * Note: if length > 19, possible scenario is to run through the string
         * to check whether the string contains only valid digits.
         * If the check had only valid digits then a negative sign meant underflow, else, overflow.
         */
        if (length - start > 19)
            throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));

        long c;
        long out = 0L;

        for ( ; start < length; start++) {
            c = (str.charAt(start) ^ '0');
            if (c > 9L)
                throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            out += c * longpow[length - start];
        }

        if (c1 == '-') {
            out = ~out + 1L;
            // If out > 0 number underflow(supposed to be negative).
            if (out > 0L)
                throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
            return out;
        }
        // If out < 0 number overflow (supposed to be positive).
        if (out < 0L)
            throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
        return out;
    }

    /**
     * parseInt(String str) parse a string into an int.
     * return 0 if string is empty.
     **/
    public static int parseInt(final String str) {
        final int length = str.length();
        if (length == 0)
            return 0;

        char c1 = str.charAt(0);
        int start;

        if (c1 == '-' || c1 == '+') {
            if (length == 1)
                throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));
            start = 1;
        } else {
            start = 0;
        }

        int out = 0; int c;
        int runlen = length - start;

        if (runlen > 9) {
            if (runlen > 10)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));

            c = (str.charAt(start) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
            if (c > 9)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            if (c > 2)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            out += c * intpow[length - start++];
        }

        for ( ; start < length; start++) {
            c = (str.charAt(start) ^ '0');
            if (c > 9)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            out += c * intpow[length - start];
        }

        if (c1 == '-') {
            out = ~out + 1;
            if (out > 0)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            return out;
        }

        if (out < 0)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        return out;
    }
}

测试代码部分。 这应该需要大约 200 秒左右。

// Int Number Parser Test;
long start = System.currentTimeMillis();
System.out.println("INT PARSER TEST");
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
   if (faiNumber.parseInt(""+i) != i)
       System.out.println("Wrong");
   if (i == 0)
       System.out.println("HalfWay Done");
}

if (faiNumber.parseInt("" + Integer.MAX_VALUE) != Integer.MAX_VALUE)
    System.out.println("Wrong");
long end = System.currentTimeMillis();
long result = (end - start);
System.out.println(result);
// INT PARSER END */

另一种方法也非常快。 请注意,未使用 int pow 数组,而是通过位移位乘以 10 的数学优化。

public static int parseInt(final String str) {
    final int length = str.length();
    if (length == 0)
        return 0;

    char c1 = str.charAt(0);
    int start;

    if (c1 == '-' || c1 == '+') {
        if (length == 1)
            throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));
        start = 1;
    } else {
        start = 0;
    }

    int out = 0;
    int c;
    while (start < length && str.charAt(start) == '0')
        start++; // <-- This to disregard leading 0. It can be
                 // removed if you know exactly your source
                 // does not have leading zeroes.
    int runlen = length - start;

    if (runlen > 9) {
        if (runlen > 10)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));

        c = (str.charAt(start++) ^ '0');  // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
        if (c > 9)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        if (c > 2)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        out = (out << 1) + (out << 3) + c; // <- Alternatively this can just be out = c or c above can just be out;
    }

    for ( ; start < length; start++) {
        c = (str.charAt(start) ^ '0');
        if (c > 9)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        out = (out << 1) + (out << 3) + c;
    }

    if (c1 == '-') {
        out = ~out + 1;
        if (out > 0)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        return out;
    }

    if (out < 0)
        throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
    return out;
}

StringInt一些方法如下:

  1. 您可以使用Integer.parseInt()

     String test = "4568"; int new = Integer.parseInt(test);
  2. 你也可以使用Integer.valueOf()

     String test = "4568"; int new = Integer.valueOf(test);

使用这个方法:

public int ConvertStringToInt(String number) {
    int num = 0;

    try {
        int newNumber = Integer.ParseInt(number);
        num = newNumber;
    } catch(Exception ex) {
        num = 0;
        Log.i("Console", ex.toString);
    }
    return num;
}

自定义算法:

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  byte bytes[] = value.getBytes();
  for (int i = 0; i < bytes.length; i++) {
    char c = (char) bytes[i];
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber)
    output *= -1;
  return output;
}

另一种解决方案:

(使用字符串charAt方法而不是将字符串转换为字节数组)

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  for (int i = 0; i < value.length(); i++) {
    char c = value.charAt(i);
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber)
    output *= -1;
  return output;
}

例子:

int number1 = toInt("20");
int number2 = toInt("-20");
int number3 = toInt("+20");
System.out.println("Numbers = " + number1 + ", " + number2 + ", " + number3);

try {
  toInt("20 Hadi");
} catch (NumberFormatException e) {
  System.out.println("Error: " + e.getMessage());
}

除了所有这些答案,我发现了一种新方法,尽管它在内部使用Integer.parseInt()

通过使用

import javafx.util.converter.IntegerStringConverter;

new IntegerStringConverter().fromString("1234").intValue()

或者

new IntegerStringConverter().fromString("1234")

尽管随着新对象的创建它有点昂贵,但我只是想在我学到一种新方法时添加。

只需通过javafx.util.StringConverter<T>类,它有助于将任何包装类值转换为字符串,反之亦然。

请使用NumberUtils从字符串中解析整数。

  • 当给定的字符串太长时,此函数也可以处理异常
  • 我们也可以给出默认值

这是示例代码。

NumberUtils.toInt("00450");
NumberUtils.toInt("45464646545645400000");
NumberUtils.toInt("45464646545645400000", 0); // Where 0 is the default value.

output:
450
0
0

Java 11 ,有几种方法可以将int转换为String类型:

1) Integer.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) Integer.decode

String str = "1234";
int result = Integer.decode(str);

将 String 转换为 int 或 Integer 是 Java 中非常常见的操作。有一些简单的方法可以处理这种基本转换。

Integer.parseInt()

主要的解决方案之一是使用 Integer 的专用静态方法:parseInt(),它返回一个原始 int 值

public class StringToInt {
public static void main(String args[]) {
    String s = "200";
    try {
        int i = Integer.parseInt(s);
        System.out.println(i);
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
   }
 }

输出:

200

默认情况下, parseInt() 方法假定给定的 String 是一个基数为 10 的整数。 此外,此方法接受另一个参数来更改此默认基数。 例如,我们可以如下解析二进制字符串

public class StringToInt {
public static void main(String args[]) {
    String givenString = "101010";

    int result = Integer.parseInt(givenString, 2);
    System.out.println(result);
  }
}

输出:

42

当然,也可以将此方法与任何其他基数一起使用,例如 16(十六进制)或 8(八进制)。

Integer.valueOf()

另一种选择是使用静态 Integer.valueOf() 方法,该方法返回一个 Integer 实例

public class StringToInt {
public static void main(String args[]) {
    String s = "200";
    try {
        Integer i = Integer.valueOf(s);  
        System.out.println(i);  
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
  }
}

输出:

200

同样,valueOf() 方法也接受自定义基数作为第二个参数

 public class StringToInt {
 public static void main(String args[]) {
    String s = "101010";
    try {
        Integer result = Integer.valueOf(givenString, 2);
        System.out.println(result);  
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
  }
}

输出:

42

Integer.decode()

此外,Integer.decode() 的工作方式与 Integer.valueOf() 类似,但也可以接受不同的数字表示

public class StringToInt {
 public static void main(String args[]) {
     String givenString = "1234";
    try {
        int result = Integer.decode(givenString);
        System.out.println(result);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
  }
}

输出:

1234

NumberFormatException 情况

如果字符串文字中没有数字,则调用 Integer.parseInt()、Integer.valueOf() 和 Integer.decode() 方法会抛出 NumberFormatException。

如果您需要原语,请使用 parseInt,否则使用 Integer.valueOf()

对于在这里结束的 Android 开发人员,这些是Kotlin的各种解决方案:

// Throws exception if number has bad form
val result1 = "1234".toInt()
// Will be null if number has bad form
val result2 = "1234"
    .runCatching(String::toInt)
    .getOrNull()
// Will be the given default if number has bad form
val result3 = "1234"
    .runCatching(String::toInt)
    .getOrDefault(0)
// Will be return of the else block if number has bad form
val result4 = "1234"
    .runCatching(String::toInt)
    .getOrElse {
        // some code
        // return an Int
    }
// As per your question "1234"  →  1234   
//using Integer.parseInt() method
public class StringToIntExample1{
 public static void main(String args[]){
 //Declaring String variable
  String s="1234";
 //Converting String into int using Integer.parseInt()
  int i=Integer.parseInt(s);
 //Printing value of i
  System.out.println(i);  
 }
} 

您可以使用 Integer.parseInt(str)

例如 :

String str = "2";

int num = Intger.parseInt(str);

如果字符串包含无效或非数字字符,则需要处理 NumberFormatException。

或者,您可以使用Integer.valueOf() 它将返回一个Integer对象。

String numberStringFormat = "10";
Integer resultIntFormat = Integer.valueOf(numberStringFormat);
LOG.info("result:" + resultIntFormat);

输出:10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM