No Image

Java lang numberformatexception for input string

СОДЕРЖАНИЕ
20 просмотров
11 марта 2020

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 6 years ago .

While running my code I am getting a NumberFormatException :

How can I prevent this exception from occurring?

5 Answers 5

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

The java.lang.NumberFormatException comes when you try to parse a non-numeric String to Number e.g. Short , Integer , Float , Double etc. For example, if you try to convert . "null" to an integer then you will get NumberFormatException. The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it’s true, "null" is not numeric. Many Java methods which convert String to numeric type e.g. Integer.parseInt() which convert String to int, Double.parseDoble() which convert String to double, and Long.parseLong() which convert String to long throws NumberFormatException to inform that the input String is not numeric.

By the way, this is not application developer’s fault. This is a data error and to solve this problem you need to correct the data. There could be nothing wrong in code if you are catching this error and printing this in the log file for data analysis, but if you are not handling this exception then your application can crash, which is not good on Java developer’s part. See Core Java Fundamentals by Cay S. Horstman to learn more about the error and exception handling in Java.

In this article, I’ll show you an example of Exception in thread "main" java.lang.NumberFormatException: For input string: "null" by creating a sample program and tell you the technique to avoid NumberFormatExcpetion in Java.

Java Program to demonstrate NumberFormatException

This is a sample Java program to demonstrate when a NumberFormatException comes. Once you go through the examples, you can reason about it. It’s pretty much common sense e.g. a null cannot be converted to a number so you will NumberFormatException. Same is true for an empty String or a non-numeric String.

One of the variants of this is a user entering a number but not in given format e.g. you expect an integer but user enters "1.0" which is a floating point literal. If you try to convert this String to Integer, you will NumberFormatException. If you are new to Java and wants to learn more about how to convert one data type to another using valueOf() , toString() and parseXX() method, please see Big Java: Early Objects 5th Edition by Cay S. Horstmann.

Читайте также:  Как набрать номер скорой с мобильного

Here is our Java program to show different scenarios where you may encounter NumberFormatException in Java:

Things are good when input is a number, now let’s enter nothing, this time, Scanner will read empty String

Please enter a number

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Main.main(Main.java:24)

Now, let’s enter null

Please enter a number
null
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Main.main(Main.java:24)

So you can say that if input is not numeric than any method which converts String to number e.g. Integer.parseInt() , Float.parseFloat() and Double.parseDouble will throw java.lang.NumberFormatException .

Please enter a number
1.0
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Main.main(Main.java:24)

This time, we got the NumberFormatException because we are trying to convert "1.0" which is a floating point String to an integer value, which is not right. If you had tried to convert "1.0" to float or double, it should have gone fine.

It’s one of the easiest error to solve, here are the steps.

1) Check the error message, this exception says for which input String it has thrown this error e.g.

Exception in thread "main" java.lang.NumberFormatException: For input string: "null" means input was null.

Exception in thread "main" java.lang.NumberFormatException: For input string: "" means input was empty String

Exception in thread "main" java.lang.NumberFormatException: For input string: "F1" means input was F1 which is alphanumeric

Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0" means input String was "1.0" and you were trying to convert it to Integral data type e.g. int, short, char and byte.

The NumberFormatException can come in any type of Java application e.g. JSP, Servlet, Android Apps, Core Java application. It’s one of the core exception and one of the most common errors in Java application after NullPointerException and NoClassDefFoundError. It’s also an unchecked exception, hence following properties of unchecked exceptions are also applicable to it.

The only way to solve this error is correct the data. Find out from where you are getting your input String and correct the data their. On the other hand, you must catch this exception whenever you are trying to convert a String to number e.g. int , short , char , byte , long , float or double as shown below:

Here is the right code to convert String to integer in Java with proper exception handling:

Читайте также:  Телефон теряет связь с сетью

The Handing exception is one of the most important coding practice for writing secure and reliable Java programs and this is also used to differentiate an average programmer with a star developer. I strongly suggest experienced Java programmers to read Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs to learn more about such practices.

That’s all about what is NumberFormatException and how to deal with it. Always remember that it’s a RuntimeException so Java will not ask you to handle it but you must otherwise your application will crash if the user enters "afafsdfds" as their age which you expect an integer. This is why validation is also very important if you are taking user input.

Sometimes a leading or trailing whitespace also cause this problem. So, make sure you trim the user input before parsing it. Alternatively, you can use Scanner’s nextInt() and hasNextInt() method to take integer input from user. Now, it’s scanner’s responsibility to parse those value and it does a good job especially with white space.

Другими словами, вы пытались разобрать "Ace of Clubs" в int чего не может сделать Java с методом Integer.parseInt . Java предоставила красивую трассировку стека, которая точно скажет вам, в чем проблема. Инструмент, который вы ищете, является отладчиком, а использование точек останова позволит вам проверить состояние вашего приложения в выбранный момент.

Решением может быть следующая логика, если вы хотите использовать синтаксический анализ:

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

Конструкторы и использование в Integer#parseInt

Они важны для понимания того, как читать трассировку стека. Посмотрите, как NumberFormatException выбрасывается из Integer#parseInt :

или позже, если формат входной String s не разбирается:

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

NumberFormatException extends IllegalArgumentException . Это говорит нам о том, что это более специализированная IllegalArgumentException . Действительно, он использовался для выделения того, что, хотя тип аргумента был правильным ( String ), содержимое String не было числовым (a, b, c, d, e, f считаются цифрами в HEX и допустимы при необходимости).

Как мне это исправить?
Ну, не фиксируй тот факт, что его бросили. Хорошо, что его бросили. Есть несколько вещей, которые вы должны рассмотреть:

  1. Можно ли прочитать трассировку стека?
  2. Является ли String которая вызывает Exception null ?
  3. Это похоже на число?
  4. Это "моя строка" или пользовательский ввод?
  5. продолжение следует

Объявление. 1.

Первая строка сообщения содержит информацию о том, что возникло исключение, и String ввода, которая вызвала проблему. Строка всегда следует : и заключена в кавычки ( "some text" ). Затем вас интересует чтение трассировки стека с конца, так как первые несколько строк – это обычно конструктор NumberFormatException , метод синтаксического анализа и т.д. Затем, в конце, есть ваш метод, в котором вы сделали ошибку. Будет указано, в каком файле он был вызван и в каком методе. Даже линия будет прикреплена. Вот увидишь. Пример того, как читать трассировку стека, приведен выше.

Читайте также:  Do not track на русском

Объявление. 2.

Когда вы видите, что вместо "For input string:" и ввода есть null (не "null" ), это означает, что вы пытались передать нулевую ссылку на число. Если вы действительно хотите обработать как 0 или любое другое число, вас может заинтересовать еще один мой пост на StackOverflow. Это доступно здесь.

Описание решения неожиданного null хорошо описано в потоке StackOverflow. Что такое исключение NullPointerException и как я могу это исправить? ,

Объявление. 3.

Если, по вашему мнению, String которая следует за кавычками : и выглядит как число, возможно, это символ, который ваша система не декодирует, или невидимый пробел. Очевидно, что " 6" не может быть проанализирован так же, как "123 " не может. Это из-за пробелов. Но может случиться так, что String будет выглядеть как "6" но на самом деле ее длина будет больше, чем количество цифр, которые вы видите.

В этом случае я предлагаю использовать отладчик или хотя бы System.out.println и распечатать длину String которую вы пытаетесь проанализировать. Если он показывает больше, чем количество цифр, попробуйте передать stringToParse.trim() в метод анализа. Если это не сработает, скопируйте всю строку после : и декодируйте ее с помощью онлайн-декодера. Он даст вам коды всех персонажей.

Есть также один случай, который я недавно обнаружил в StackOverflow , который вы могли видеть, что вход выглядит как число, например, "1.86" и он содержит только эти 4 символа, но ошибка все еще существует. Помните, с помощью # Integer # parseInt # можно анализировать только целые числа. Для разбора десятичных чисел следует использовать Double#parseDouble .

Другая ситуация, когда число имеет много цифр. Возможно, он слишком большой или слишком маленький, чтобы соответствовать int или long . Возможно, вы захотите попробовать new BigDecimal( ) .

Объявление. 4.

Наконец мы подошли к тому месту, в котором мы согласны, что мы не можем избежать ситуаций, когда пользователь вводит "abc" в виде числовой строки. Зачем? Потому что он может. В счастливом случае это потому, что он тестер или просто выродок. В плохом случае это злоумышленник.

Что я могу сделать сейчас? Что ж, Java дает нам try-catch вы можете сделать следующее:

Комментировать
20 просмотров
Комментариев нет, будьте первым кто его оставит

Это интересно
No Image Компьютеры
0 комментариев
No Image Компьютеры
0 комментариев
Adblock
detector