问题:如何在Java中将String转换为int?

如何在Java中将String转换为int

我的字符串仅包含数字,我想返回它代表的数字。

例如,给定字符串"1234",结果应为数字1234

标签:java,string,int,type-conversion

Q: How do I convert a String to an int in Java?

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

回答1:

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)

A1:

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

If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:

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

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

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

回答2:

例如,以下两种方法:

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

这些方法之间略有不同:

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

对于所有情况都是如此:Short.valueOf / parseShortLong.valueOf / parseLong,等

A2:

For example, here are two ways:

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

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

回答3:

嗯,要考虑的非常重要的一点是,整数解析器会引发 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.
}

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

A3:

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in 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.
}

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

回答4:

手动执行:

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

A4:

Do it manually:

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

回答5:

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

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

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

Apache NumberUtils API版本3.4

A5:

An alternate solution is to use Apache Commons' NumberUtils:

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

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

回答6:

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

首先要做的是接收输入,在这种情况下,是一串数字;我将其称为Stringnumber,在这种情况下,我将使用数字12来举例说明它,因此Stringnumber="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,因此我们无法进行任何数学运算。

我们正在将后者(最后一位)除以10,方法是2/10=0.2(因此为什么要加倍),如下所示:

 lastdigit = lastdigit/10;

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

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

在数学上不用太费力,我们只是在将数字的位数分隔开。您会看到,因为我们只考虑0-9,所以除以10的倍数就像在存储它的位置创建一个"盒子"(回想一下一年级老师向您解释单位是100的时候)。所以:

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

然后您就去了。考虑到以下限制,您将一个数字字符串(在本例中为两个数字)转换为由这两个数字组成的整数:

  • 没有重复周期
  • 没有"魔术"表达式,例如parseInt

A6:

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

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

Having the codes, we just need to look up at the table, and make the necessary adjustments:

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

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

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

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

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

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No "Magic" Expressions such as parseInt

回答7:

Integer.decode

您还可以使用公共静态整数解码(Stringnm)引发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();
    

A7:

Integer.decode

You can also use public static Integer decode(String nm) throws NumberFormatException.

It also works for base 8 and 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

If you want to get int instead of Integer you can use:

  1. Unboxing:

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

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

回答8:

只要给定String不包含Integer的可能性极小,就必须处理这种特殊情况。可悲的是,标准Java方法Integer::parseIntInteger::valueOf抛出一个NumberFormatException以表示这种特殊情况。因此,您必须对流控制使用异常,这通常被认为是不良的编码风格。

我认为,应通过返回Optional 处理这种特殊情况。由于Java不提供这种方法,因此我使用以下包装器:

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

用法:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

虽然这仍在内部使用异常进行流控制,但是用法代码变得非常干净。

A8:

Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

In my opinion, this special case should be handled by returning an Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

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

Usage:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

While this is still using exceptions for flow control internally, the usage code becomes very clean.

回答9:

将字符串转换为整数比仅转换数字更复杂。您已经考虑了以下问题:

  • 字符串是否仅包含数字 0-9
  • 在字符串之前或之后,-/ + 是怎么回事?有可能吗(指帐号)?
  • MAX _- / MIN_INFINITY怎么办??如果字符串为99999999999999999999,会发生什么?机器可以将此字符串视为int吗?

A9:

Converting a string to an int is more complicated than just convertig a number. You have think about the following issues:

  • Does the string only contains numbers 0-9?
  • What's up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
  • What's up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?

回答10:

方法:

 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 中的最后2种方法以及有关转换的大文章此处

A10:

Methods to do that:

 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 produces Integer object, all other methods - primitive int.

Last 2 methods from commons-lang3 and big article about converting here.

回答11:

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

例如:

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

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

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

我们还可以使用 toInt(StringstrValue) /commons/lang3/math/NumberUtils.html">NumberUtils实用程序类进行转换:

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

A11:

We can use the parseInt(String str) method of the Integer wrapper class for converting a String value to an integer value.

For example:

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

The Integer class also provides the valueOf(String str) method:

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

We can also use toInt(String strValue) of NumberUtils Utility Class for the conversion:

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

回答12:

使用 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或类似值)

只有一种例外: < code> NumberFormatException

A12:

Use Integer.parseInt(yourString).

Remember the following things:

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

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

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

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

Integer.parseInt(""); // Exception (not 0 or something)

There is only one type of exception: NumberFormatException

回答13:

我有一个解决方案,但是我不知道它有多有效。但是它运作良好,我认为您可以改善它。另一方面,我对 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));
        }
    }
}

A13:

I'm have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:

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

Testing with 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));
        }
    }
}

回答14:

Google Guava 具有 tryParse(String),返回如果无法解析字符串,则为null,例如:

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

A14:

Google Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

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

回答15:

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

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

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

A15:

You can also begin by removing all non-numerical characters and then parsing the integer:

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

But be warned that this only works for non-negative numbers.

回答16:

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

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

A16:

Apart from the previous answers, I would like to add several functions. These are results while you use them:

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
}

Implementation:

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

回答17:

在某些预防措施下,您也可以使用此代码。

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

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

A17:

You can use this code also, with some precautions.

  • Option #1: Handle the exception explicitly, for example, showing a message dialog and then stop the execution of the current workflow. For example:

    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;
    }
    
  • Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.

回答18:

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

A18:

You can use new Scanner("1244").nextInt(). Or ask if even an int exists: new Scanner("1244").hasNextInt()

回答19:

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

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

A19:

In programming competitions, where you're assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don't need any of that) and will be a bit more efficient.

  1. For valid positive integer:

    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. For both positive and negative integers:

    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. If you are expecting a whitespace before or after these numbers, then make sure to do a str = str.trim() before processing further.

回答20:

如上所述,Apache Commons的NumberUtils可以做到。如果无法将字符串转换为整数,则返回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;

A20:

As mentioned, Apache Commons' NumberUtils can do it. It returns 0 if it cannot convert a string to an int.

You can also define your own default value:

NumberUtils.toInt(String str, int defaultValue)

Example:

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;

回答21:

您可以尝试以下方法:

  • 使用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

A21:

Simply you can try this:

  • Use Integer.parseInt(your_string); to convert a String to int
  • Use Double.parseDouble(your_string); to convert a String to double

Example

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

回答22:

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

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

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

Integer.parseInt(myBuilderOrBuffer.toString());

A22:

For a normal string you can use:

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

For a String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());

回答23:

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

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

A23:

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

Make sure there is no non-numeric data in the string.

回答24:

我很惊讶没有人提到将String作为参数的Integer构造函数。

所以,这里是:

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

Java 8-Integer(String)

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


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

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

A24:

I am a little bit surprised that nobody mentioned the Integer constructor that takes String as a parameter.

So, here it is:

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

Java 8 - Integer(String).

Of course, the constructor will return type Integer, and an unboxing operation converts the value to int.


It's important to mention: This constructor calls the parseInt method.

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

回答25:

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

A25:

Use Integer.parseInt() and put it inside a try...catch block to handle any errors just in case a non-numeric character is entered, for example,

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

回答26:

我们在这里

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

A26:

Here we go

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

回答27:

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

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

String number = "999";

1)使用Ints.tryParse

int result = Ints.tryParse(number);

2)使用NumberUtils.createInteger

Integer result = NumberUtils.createInteger(number);

3)使用NumberUtils.toInt

int result = NumberUtils.toInt(number);

4)使用Integer.valueOf

Integer result = Integer.valueOf(number);

5)使用Integer.parseInt

int result = Integer.parseInt(number);

6)使用Integer.decode

int result = Integer.decode(number);

7)使用Integer.parseUnsignedInt

int result = Integer.parseUnsignedInt(number);

A27:

It can be done in seven ways:

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

String number = "999";

1) Using Ints.tryParse:

int result = Ints.tryParse(number);

2) Using NumberUtils.createInteger:

Integer result = NumberUtils.createInteger(number);

3) Using NumberUtils.toInt:

int result = NumberUtils.toInt(number);

4) Using Integer.valueOf:

Integer result = Integer.valueOf(number);

5) Using Integer.parseInt:

int result = Integer.parseInt(number);

6) Using Integer.decode:

int result = Integer.decode(number);

7) Using Integer.parseUnsignedInt:

int result = Integer.parseUnsignedInt(number);

回答28:

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

  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
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s,defaultValue)

A28:

You could use any of following:

  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)

回答29:

这是一个 complete 程序,所有条件都为正和负,而无需使用库

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

A29:

This is a complete program with all conditions positive and negative without using a library

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

回答30:

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

A30:

One method is parseInt(String). It returns a primitive int:

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

The second method is valueOf(String), and it returns a new Integer() object:

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
回到顶部