Java parseint without exception

Convert String to Integer with default value

I want to convert a java.lang.String to a java.lang.Integer , assigning a default value of 0 if the String is not convertible. Here is what I came up with. I would appreciate an assesment of this approach. To be honest, it feels a little squirrely to me:

String strCorrectCounter = element.getAttribute("correct"); Integer iCorrectCounter = new Integer(0); try < iCorrectCounter = new Integer(strCorrectCounter); >catch (Exception ignore)

7 Answers 7

int tryParseInt(String value) < try < return Integer.parseInt(value); >catch(NumberFormatException nfe) < // Log exception. return 0; >> 

you should catch NumberFormatException instead of exception.

\$\begingroup\$ +1 for catching the correct exception and using parseInt() so a cached Integer can be returned instead of guaranteeing that a new instance is returned. \$\endgroup\$

I’d consider using NumberUtils.toInt from Apache Commons Lang which does exactly this:

public static int NumberUtils.toInt(java.lang.String str, int defaultValue) 

See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK’s built-in libraries but I think the reasoning could be true for other libraries too.)

Читайте также:  Python 3 and wxpython

\$\begingroup\$ excellent suggestion! I am very thankful for the Apache Commons libraries. \$\endgroup\$

As others have noted, your code should never catch Exception. Doing so causes all sorts of problems. In addition to the answers given I would also suggest that you don’t default the value to 0 but make it more generic. For example

public static int parseInteger( String string, int defaultValue ) < try < return Integer.parseInt(string); >catch (NumberFormatException e ) < return defaultValue; >> 

You should not use new Integer( string ) instead use Integer.valueOf( string ) . As discussed before in many other threads, valueOf may be faster due to the fact it can lookup small integer values and reduces the overhead of creating a new object.

Just to be a bit(?) pedantic:

public static final int iDEFAULT_DEFAULT_PARSED_INT = 0; public static int ifIntFromString( String sToParse) < return ifIntFromString( sToParse, iDEFAULT_DEFAULT_PARSED_INT ); >public static int ifIntFromString( String sToParse, int iDefaultValue ) < int iReturnValue = null; try < iReturnValue = Integer.parseInt(sToParse); >catch ( NumberFormatException e ) < iReturnValue = iDefaultValue; >assert (null != iReturnValue) : "Impossible - no return value has been set!"; return iReturnValue; > 

It would be really great if there were a way to accomplish this without having to catch an exception (due to performance concerns) and without having to write the parsing code yourself — but this is what the base libraries give us.

\$\begingroup\$ @assylias : Well, it is only necessary in order to maintain a high level of pedanticism. 🙂 \$\endgroup\$

\$\begingroup\$ @palacsint Ack! Thanks — bother. Too many languages — my apologies. In Java, null is a first-order token having identity only with itself (if I recall correctly) whereas in many other languages (such as C/C++) it equates to the integer zero. In this instance, my intent was to use null as the «non-value» to indicate a failure to set the variable while still having it be initialized. I ought to have used an Integer object rather than an int type, then converted the Integer to an int for the return value. \$\endgroup\$

Parsing Methods in Java Convert String to Int

In Java there are two methods to convert String to Int, they are:

Integer.parseInt() Integer.valueOf() 
  1. Convert String to Int using Integer.parseInt() The Integer.parseInt() is a static method of Integer class used in Java to converts string to primitive integer.

String ‘100’ to primitive integer 100

Note:Parsing is a process of converting one data type to another. For example String to integer. Coding part please refer this: best way to convert string to int

The performance cost of creating and throwing an Exception in Java can, and normally always is significantly more taxing than pre-validating a value can be converted. For all JVM’s I am aware of (IBM’s Java, Oracle’s Java, OpenJDK, etc.) the cost of the exception also often linearly scales relative to the depth of the call stack when the exception is thrown, so deeply-nested exceptions are more costly than exceptions in the main-method.

The bottom line is that in good code you should never (with very few exceptions) make exceptions part of the normal/expected flow of the code.

So, in your case, I would minimalize the possibility of exceptions by trying as hard as reasonable to eliminate exception cases, while still handling the exceptions appropriately.

Note that the documentation for Double.valueOf(String) alludes to this and also provides a regular expression useful for checking whether valueOf may throw an exception.

private static final Pattern isInteger = Pattern.compile("[+-]?\\d+"); public static final int tryParseInt(String value) < if (value == null || !isInteger.matcher(value).matches()) < return 0; >try < return Integer.parseInt(value); >catch(NumberFormatException nfe) < return 0; >> 

While the additional checks may slow down valid numbers slightly, it drastically improves the performance of handling invalid numbers in the majority of the cases, and the trade-off is, in my experience more than worth it.

Источник

Вопрос-ответ: как в Java правильно конвертировать String в int?

Java-университет

int в String — очень просто, и вообще практически любой примитивный тип приводится к String без проблем.

 int x = 5; String text = "X lang-java line-numbers">int i = Integer.parseInt (myString);

Если строка, обозначенная переменной myString , является допустимым целым числом, например «1», «200», Java спокойно преобразует её в примитивный тип данных int . Если по какой-либо причине это не удается, подобное действие может вызвать исключение NumberFormatException , поэтому чтобы программа работала корректно для любой строки, нам нужно немного больше кода. Программа, которая демонстрирует метод преобразования Java String в int , управление для возможного NumberFormatException :

 public class JavaStringToIntExample < public static void main (String[] args) < // String s = "fred"; // используйте это, если вам нужно протестировать //исключение ниже String s = "100"; try < // именно здесь String преобразуется в int int i = Integer.parseInt(s.trim()); // выведем на экран значение после конвертации System.out.println("int i = " + i); >catch (NumberFormatException nfe) < System.out.println("NumberFormatException: " + nfe.getMessage()); >> 

Обсуждение

Когда вы изучите пример выше, вы увидите, что метод Integer.parseInt (s.trim ()) используется для превращения строки s в целое число i , и происходит это в следующей строке кода:

int i = Integer.parseInt (s.trim ())
  • Integer.toString (int i) используется для преобразования int в строки Java.
  • Если вы хотите преобразовать объект String в объект Integer (а не примитивный класс int ), используйте метод valueOf () для класса Integer вместо метода parseInt () .
  • Если вам нужно преобразовать строки в дополнительные примитивные поля Java, используйте такие методы, как Long.parseLong () и ему подобные.

Источник

Java String to int Conversion – 10 Examples

Java String to int conversion can be done using the Integer wrapper class. There are two static methods for this purpose – parseInt() and valueOf().

Java String to int Conversion Methods

The Integer class provides 5 overloaded methods for the string to int conversion.

  • parseInt(String s): parses the string as a signed decimal value. The string should have only decimal digits. The first character can be ASCII minus sign (-) or plus sign (+).
  • parseInt(String s, int radix): parses the given string as the signed integer in the radix.
  • parseInt(CharSequence s, int beginIndex, int endIndex, int radix): The method is useful in parsing a substring to an integer. If the index values are invalid, IndexOutOfBoundsException is thrown. If the CharSequence is null, NullPointerException is thrown.
  • valueOf(String s): This method returns an Integer object. The string is parsed as a signed decimal value. It calls parseInt (s, 10) internally.
  • valueOf(String s, int radix): internally calls the parseInt(s, radix) method and returns the Integer object.

Important Points for String to int Parsing

  • All the parseInt() and valueOf() methods throw NumberFormatException if the string is not parsable.
  • The radix value should be in the supported range i.e. from Character.MIN_RADIX (2) to Character.MAX_RADIX(36), otherwise NumberFormatException is thrown.
  • The parseInt() methods return int primitive data type.
  • The valueOf() methods return an Integer object.
  • The valueOf() methods internally calls parseInt() methods.
  • Since Java supports autoboxing, we can use int and Integer in our program interchangeably. So we can use either parseInt() or valueOf() method to convert a string to integer.
  • The parseInt() method to parse substring was added to String class in Java 9 release.
  • The string should not contain the prefix used to denote an integer in the different radix. For example, “FF” is valid but “0xFF” is not a valid string for the conversion.
  • The valueOf() methods are present because it’s present in every wrapper class and String to convert other data types to this object. Recommended Read: Java String valueOf() method.

Java String to integer Examples

Let’s look at some examples for parsing a string to an integer using the parseInt() and valueOf() methods.

1. parseInt(String s)

jshell> Integer.parseInt("123"); $69 ==> 123 jshell> Integer.parseInt("-123"); $70 ==> -123 jshell> Integer.parseInt("+123"); $71 ==> 123 jshell> Integer.parseInt("-0"); $72 ==> 0 jshell> Integer.parseInt("+0"); $73 ==> 0

2. parseInt(String s, int radix)

jshell> Integer.parseInt("FF", 16); $74 ==> 255 jshell> Integer.parseInt("1111", 2); $75 ==> 15

3. parseInt(CharSequence s, int beginIndex, int endIndex, int radix)

jshell> String line = "Welcome 2019"; line ==> "Welcome 2019" jshell> Integer.parseInt(line, 8, 12, 10) $77 ==> 2019 jshell> String lineMixed = "5 in binary is 101"; lineMixed ==> "5 in binary is 101" jshell> Integer.parseInt(lineMixed, 0, 1, 10) $79 ==> 5 jshell> Integer.parseInt(lineMixed, 15, 18, 2) $80 ==> 5

Java String To Int Example

4. valueOf(String s)

jshell> Integer io = Integer.valueOf(123); io ==> 123 jshell> int i = Integer.valueOf(123); i ==> 123

The valueOf() method returns Integer object. But, we can assign it to int also because Java supports autoboxing.

5. valueOf(String s, int radix)

jshell> Integer.valueOf("F12", 16) $84 ==> 3858 jshell> int i = Integer.valueOf("F12", 16) i ==> 3858 jshell> int i = Integer.valueOf("077", 8) i ==> 63

6. NumberFormatException Example

jshell> Integer.parseInt("abc"); | Exception java.lang.NumberFormatException: For input string: "abc" | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at Integer.parseInt (Integer.java:776) | at (#87:1) jshell> Integer.parseInt("FF", 8); | Exception java.lang.NumberFormatException: For input string: "FF" under radix 8 | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at (#88:1) jshell>

7. NullPointerException when parsing substring

jshell> Integer.parseInt(null, 1, 2, 10); | Exception java.lang.NullPointerException | at Objects.requireNonNull (Objects.java:221) | at Integer.parseInt (Integer.java:701) | at (#89:1) jshell>

8. IndexOutOfBoundsException when parsing substring

jshell> Integer.parseInt("Hello 2019", 1, 100, 10); | Exception java.lang.IndexOutOfBoundsException | at Integer.parseInt (Integer.java:704) | at (#90:1) jshell>

9. NumberFormatException when radix is out of range

jshell> Integer.parseInt("FF", 50); | Exception java.lang.NumberFormatException: radix 50 greater than Character.MAX_RADIX | at Integer.parseInt (Integer.java:629) | at (#91:1) jshell>

10. Java String to int Removing Leading Zeroes

If the string is prefixed with zeroes, they are removed when converted to int.

jshell> Integer.parseInt("00077"); $95 ==> 77 jshell> Integer.parseInt("00077", 16); $96 ==> 119 jshell> Integer.parseInt("00077", 12); $97 ==> 91 jshell> Integer.parseInt("00077", 8); $98 ==> 63

Conclusion

Java String to int conversion is very easy. We can use either parseInt() or valueOf() method. Java 9 added another utility method to parse substring to an integer.

References:

Источник

Оцените статью