Java string to int java lang numberformatexception

How to convert String to int in Java

In Java, we can use Integer.parseInt(String) to convert a String to an int ; For unparsable String, it throws NumberFormatException .

 Integer.parseInt("1"); // ok Integer.parseInt("+1"); // ok, result = 1 Integer.parseInt("-1"); // ok, result = -1 Integer.parseInt("100"); // ok Integer.parseInt(" 1"); // NumberFormatException (contains space) Integer.parseInt("1 "); // NumberFormatException (contains space) Integer.parseInt("2147483648"); // NumberFormatException (Integer max 2,147,483,647) Integer.parseInt("1.1"); // NumberFormatException (. or any symbol is not allowed) Integer.parseInt("1-1"); // NumberFormatException (- or any symbol is not allowed) Integer.parseInt(""); // NumberFormatException, empty Integer.parseInt(" "); // NumberFormatException, (contains space) Integer.parseInt(null); // NumberFormatException, null 

1. Convert String to int

Below example uses Integer.parseInt(String) to convert a String «1» to a primitive type int .

 package com.mkyong.string; public class ConvertStringToInt < public static void main(String[] args) < String number = "1"; // String to int int result = Integer.parseInt(number); // 1 System.out.println(result); >> 

2.How to handle NumberFormatException

2.1 For invalid number or unparsable String, the Integer.parseInt(String) throws NumberFormatException .

 String number = "1A"; int result = Integer.parseInt(number); // throws NumberFormatException 
 Exception in thread "main" java.lang.NumberFormatException: For input string: "1A" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:786) at com.mkyong.string.ConvertStringToInt.main(ConvertStringToInt.java:18) 

2.2 The best practice is catch the NumberFormatException during the conversion.

 package com.mkyong.string; public class ConvertStringToInt < public static void main(String[] args) < String number = "1A"; try < int result = Integer.parseInt(number); System.out.println(result); >catch (NumberFormatException e) < //do something for the exception. System.err.println("Invalid number format : " + number); >> > 
 Invalid number format : 1A 

3. Integer.MAX_VALUE = 2147483647

Be careful, do not convert any numbers greater than 2,147,483,647, which is Integer.MAX_VALUE ; Otherwise, it will throw NumberFormatException .

 package com.mkyong.string; public class ConvertStringToInt2 < public static void main(String[] args) < // 2147483647 System.out.println(Integer.MAX_VALUE); String number = "2147483648"; try < int result = Integer.parseInt(number); System.out.println(result); >catch (NumberFormatException e) < //do something for the exception. System.err.println("Invalid number format : " + number); >> > 
 2147483647 Invalid number format : 2147483648 

4. Integer.parseInt(String) vs Integer.valueOf(String)

The Integer.parseInt(String) convert a String to primitive type int ; The Integer.valueOf(String) convert a String to a Integer object. For unparsable String, both methods throw NumberFormatException .

 int result1 = Integer.parseInt("1"); Integer result2 = Integer.valueOf("1"); 

5. Download Source Code

6. References

Источник

Читайте также:  Python set add many

Понимание исключения NumberFormatException в Java

Поскольку он не отмечен , Java не заставляет нас обрабатывать или объявлять его.

В этом кратком руководстве мы опишем и продемонстрируем , что вызывает исключение NumberFormatException в Java и как его избежать или справиться с ним .

2. Причины исключения NumberFormatException ​

Существуют различные проблемы, вызывающие NumberFormatException . Например, некоторые конструкторы и методы в Java вызывают это исключение.

Мы обсудим большинство из них в разделах ниже.

2.1. Нечисловые данные, переданные конструктору

Давайте рассмотрим попытку создания объекта Integer или Double с нечисловыми данными.

Оба этих утверждения вызовут NumberFormatException :

 Integer aIntegerObj = new Integer("one");   Double doubleDecimalObj = new Double("two.2"); 

Давайте посмотрим на трассировку стека, которую мы получили, когда передали неверный ввод «один» конструктору Integer в строке 1:

 Exception in thread "main" java.lang.NumberFormatException: For input string: "one"   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)   at java.lang.Integer.parseInt(Integer.java:580)   at java.lang.Integer.init>(Integer.java:867)   at MainClass.main(MainClass.java:11) 

Он выдал NumberFormatException . Конструктор Integer потерпел неудачу при попытке понять ввод с помощью parseInt() внутренне.

Java Number API не преобразует слова в числа, поэтому мы можем исправить код, просто изменив его на ожидаемое значение:

 Integer aIntegerObj = new Integer("1");   Double doubleDecimalObj = new Double("2.2"); 

2.2. Разбор строк, содержащих нечисловые данные

Подобно поддержке синтаксического анализа в конструкторе в Java, у нас есть специальные методы синтаксического анализа, такие как par seInt(), parseDouble(), valueOf() и decode() .

Если мы попытаемся сделать те же самые виды преобразования с ними:

 int aIntPrim = Integer.parseInt("two");   double aDoublePrim = Double.parseDouble("two.two");   Integer aIntObj = Integer.valueOf("three");   Long decodedLong = Long.decode("64403L"); 

Тогда мы увидим такое же ошибочное поведение.

И мы можем исправить их аналогичным образом:

 int aIntPrim = Integer.parseInt("2");   double aDoublePrim = Double.parseDouble("2.2");   Integer aIntObj = Integer.valueOf("3");   Long decodedLong = Long.decode("64403"); 

2.3. Передача строк с посторонними символами

Или, если мы попытаемся преобразовать строку в число с посторонними данными на входе, такими как пробелы или специальные символы:

 Short shortInt = new Short("2 ");   int bIntPrim = Integer.parseInt("_6000"); 

Тогда у нас будет та же проблема, что и раньше.

Мы могли бы исправить это, немного поработав со строками:

 Short shortInt = new Short("2 ".trim());   int bIntPrim = Integer.parseInt("_6000".replaceAll("_", ""));   int bIntPrim = Integer.parseInt("-6000"); 

Обратите внимание, что здесь, в строке 3, допускаются отрицательные числа , используя символ дефиса в качестве знака минус.

2.4. Форматы чисел, зависящие от локали

Давайте рассмотрим частный случай номеров, зависящих от локали. В европейских регионах запятая может обозначать десятичный разряд. Например, «4000,1» может представлять десятичное число «4000,1».

По умолчанию мы получим NumberFormatException , пытаясь разобрать значение, содержащее запятую:

 double aDoublePrim = Double.parseDouble("4000,1"); 

Нам нужно разрешить запятые и избежать исключения в этом случае. Чтобы сделать это возможным, Java должна понимать запятую здесь как десятичную.

Мы можем разрешить запятые для европейского региона и избежать исключения, используя NumberFormat .

Давайте посмотрим на это в действии, используя Locale для Франции в качестве примера:

 NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE);   Number parsedNumber = numberFormat.parse("4000,1");   assertEquals(4000.1, parsedNumber.doubleValue());   assertEquals(4000, parsedNumber.intValue()); 

3. Лучшие практики​

Давайте поговорим о нескольких хороших практиках, которые могут помочь нам справиться с NumberFormatException :

  1. Не пытайтесь преобразовать буквенные или специальные символы в числа — Java Number API не может этого сделать.
  2. Мы можем захотеть проверить входную строку с помощью регулярных выражений и выдать исключение для недопустимых символов .
  3. Мы можем дезинфицировать ввод от предсказуемых известных проблем с помощью таких методов, как trim() и replaceAll() .
  4. В некоторых случаях допустимы вводимые специальные символы. Поэтому мы делаем для этого специальную обработку, например, с помощью NumberFormat , который поддерживает множество форматов .

4. Вывод​

В этом руководстве мы обсудили исключение NumberFormatException в Java и его причины. Понимание этого исключения может помочь нам создавать более надежные приложения.

Кроме того, мы научились избегать исключений с некоторыми недопустимыми входными строками.

Наконец, мы увидели несколько лучших практик для работы с NumberFormatException .

Как обычно, исходный код, использованный в примерах, можно найти на GitHub .

Источник

How to Handle the NumberFormat Exception in Java

How to Handle the NumberFormat Exception in Java

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float). For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.

Since the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

What Causes NumberFormatException

There can be various cases related to improper string format for conversion to numeric values. Some of them are:

Null input string

Empty input string

Input string with leading/trailing whitespaces

Integer myInt = new Integer(" 123 ");

Input string with inappropriate symbols

Input string with non-numeric data

Integer.parseInt("Twenty Two");

Alphanumeric input string

Input string exceeding the range of the target data type

Integer.parseInt("12345678901");

Mismatch of data type between input string and the target data type

NumberFormatException Example

Here is an example of a NumberFormatException thrown when attempting to convert an alphanumeric string to an integer:

public class NumberFormatExceptionExample < public static void main(String args[]) < int a = Integer.parseInt("1a"); System.out.println(a); > >

In this example, a string containing both numbers and characters is attempted to be parsed to an integer, leading to a NumberFormatException:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1a" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)

Such operations should be avoided where possible by paying attention to detail and making sure strings attempted to be parsed to numeric values are appropriate and legal.

How to Handle NumberFormatException

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an NumberFormatException in try-catch blocks
  • Catch the NumberFormatException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.

The code in the earlier example can be updated with the above steps:

public class NumberFormatExceptionExample < public static void main(String args[]) < try < int a = Integer.parseInt("1a"); System.out.println(a); > catch (NumberFormatException nfe) < System.out.println("NumberFormat Exception: invalid input string"); > System.out.println("Continuing execution. "); > >

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

NumberFormat Exception: invalid input string Continuing execution. 

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

Источник

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