For input string ошибка перевод

Делаю задачу в Intellij IDEA, при запуске дает ввести первую строку, при нажатии enter выдает исключение :
Exception in thread «main» java.lang.NumberFormatException: For input string: «string»
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javarush.task.task07.task0706.Solution.main(Solution.java:19)

Process finished with exit code 1
Это происходит уже не с первой задачей, такое ощущение, что проверка запускается не для текущей задачи, а для одной из выполненных перед ней. Я пробовала удалить плагин javarush и установить его заново, ничего не поменялось, не пойму, почему так происходит или действительно ошибка в текущей задаче.

package com.javarush.task.task07.task0711;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

/*
Удалить и вставить
*/

public class Solution {
public static void main(String[] args) throws Exception {
ArrayList <String> list = new ArrayList <String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 5; i++) {
String s = reader.readLine();
list.add(s);
}
for (int i = 0; i < 13; i++) {
list.get(list.size() — 1);
list.remove(list.size() — 1);
list.set(0, list.get(list.size() — 1));
}
for (int i = 0; i < list.size(); i++) {
System.out.println (list.get(i));
}
}
}

glebasik0

0 / 0 / 0

Регистрация: 10.04.2017

Сообщений: 8

1

03.11.2017, 05:41. Показов 15741. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Считываю из файла строку: asdasdasd112 sada 1 123dfdsd
Выбрал только цифры, получилось так: 112 1 123
Пытаюсь убрать лишние пробелы, а у меня выдаёт эту ошибку: java.lang.NumberFormatException: For input string: «»
Ошибка возникает в этой части кода:

Java
1
2
3
4
5
6
7
8
9
10
11
12
            int s = 0;
            int j = 0;
            List<String> ListChisel = new ArrayList<String>();
            ListChisel = Arrays.asList(massPosled2);
            for (int i = 0; i < ListChisel.size(); i++) {
                if (Character.isSpaceChar(Integer.parseInt(ListChisel.get(i)))){
                    ListChisel.remove(i);
                    j++;
                } else{
                    s++;
                }
            }

Но на всякий случай вот весь код:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.company;
 
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Main {
 
    public static void main(String args[]) throws IOException {
        FileInputStream fileIn = null;
 
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            File f = new File("in.txt");
            BufferedReader fin = new BufferedReader(new FileReader(f));
            String line = fin.readLine();
            System.out.println(line);
 
            String num = "";
 
            char[] c = line.toCharArray();
            System.out.println(c);
            for (int i = 0; i < c.length; i++){
                if(Character.isDigit(c[i])||c[i]==' '){
                    num+=c[i];
                }else {
 
                }
            }
 
            String chisla = num.toString();
            String massPosled[] = chisla.split(" ");
            String massPosled2[] = new String[massPosled.length];
            for (int i = 0; i < massPosled.length; i++) {
                if (massPosled[i] == "") {
 
                } else {
                    massPosled2[i] = massPosled[i];
                    System.out.println(massPosled2[i]);
                }
            }
 
            int s = 0;
            int j = 0;
            List<String> ListChisel = new ArrayList<String>();
            ListChisel = Arrays.asList(massPosled2);
            for (int i = 0; i < ListChisel.size(); i++) {
                if (Character.isSpaceChar(Integer.parseInt(ListChisel.get(i)))){
                    ListChisel.remove(i);
                    j++;
                } else{
                    s++;
                }
            }
 
 
        }finally {
            if (fileIn != null) {
                fileIn.close();
            }
        }
    }
}



0



al1as

386 / 74 / 31

Регистрация: 13.04.2012

Сообщений: 127

03.11.2017, 07:00

2

Я бы вообще весь ваш код с заполнением листа после 17 строки заменил на:

Java
1
2
3
4
5
6
Matcher matcher = Pattern.compile(".*?(\d+)").matcher(line);
            
List<String> ListChisel = new ArrayList<>();
while (matcher.find()) {
    ListChisel.add(matcher.group(1));
}

А у вас ошибка в 36 строке: строки нужно сравнивать через equals. После этого у вас в массиве на месте пустого символа окажется элемент null. Избавиться от него при создании листа можно такой строкой

Java
1
List<String> ListChisel = Arrays.stream(massPosled2).filter(Objects::nonNull).collect(Collectors.toList());

Либо вручную создавать лист и при добавлении элементов проверять на null (но не использовать Arrays.asList(), т.к. он создает лист фиксированного размера, и удалить из него ничего не выйдет).

Добавлено через 9 минут
Если будете пробовать мой вариант, не забудьте добавить импорты:

Java
1
2
import java.util.regex.Matcher;
import java.util.regex.Pattern;



0



746 / 493 / 285

Регистрация: 10.09.2015

Сообщений: 1,530

03.11.2017, 12:58

3

(Character.isSpaceChar(Integer.parseInt(ListChisel.get(i)) — ты пытаешься пробел перевести в число, вот тебе и ошибка



0



Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:UsersqasimAppDataLocalNetBeansCache8.1executor-snippetsrun.xml:53: Java returned: 1

means:

There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "Ace of Clubs".
at line 65th of NumberFormatException.java which is a constructor,
which was invoked from Integer.parseInt() which is in file Integer.java in line 580,
which was invoked from Integer.parseInt() which is in file Integer.java in line 615,
which was invoked from method main in file Cards.java in line 68.

It has resulted in exit code 1

In other words, you tried to parse "Ace of Clubs" to an int what Java can’t do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you’re looking for is debugger and using breakpoints will allow you to inspect the state of you application at the chosen moment.

The solution might be the following logic in case you want to use parsing:

if (cards[index].startsWith("Ace")) 
    value = 1;
else if (cards[index].startsWith("King"))
    value = 12;
else if (cards[index].startsWith("Queen"))
    value = 11;
...
else {
    try {
        Integer.parseInt(string.substring(0, cards[index].indexOf(" "))); 
    } catch (NumberFormatException e){
        //something went wrong
    }
}

What is an Exception in Java?

An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program’s instructions.

-Documentation

Constructors and usage in Integer#parseInt

static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: "" + s + """);
}

public NumberFormatException (String s) {
    super (s);
}

They are important for understanding how to read the stacktrace. Look how the NumberFormatException is thrown from Integer#parseInt:

if (s == null) {
    throw new NumberFormatException("null");
}

or later if the format of the input String s is not parsable:

throw NumberFormatException.forInputString(s); 

What is a NumberFormatException?

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

-Documentation

NumberFormatException extends IllegalArgumentException. It tells us that it’s more specialized IllegalArgumentException. Indeed, it’s used for highlighting that although, the argument type was correct (String) the content of the String wasn’t numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).

How do I fix it?
Well, don’t fix the fact that it’s thrown. It’s good that it’s thrown. There are some things you need to consider:

  1. Can I read the stacktrace?
  2. Is the String which causes an Exception a null?
  3. Does it look like a number?
  4. Is it ‘my string’ or user’s input?
  5. to be continued

Ad. 1.

The first line of a message is an information that the Exception occurred and the input String which caused the problem. The String always follows : and is quoted ("some text"). Then you become interested in reading the stacktrace from the end, as the first few lines are usually NumberFormatException‘s constructor, parsing method etc. Then at the end, there is your method in which you made a bug. It will be pointed out in which file it was called and in which method. Even a line will be attached. You’ll see. The example of how to read the stacktrace is above.

Ad. 2.

When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It’s available here.

The description of solving unexpected nulls is well described on StackOverflow thread What is a NullPointerException and how can I fix it?.

Ad. 3.

If the String that follows the : and is quoted looks like a number in your opinion, there might be a character which your system don’t decode or an unseen white space. Obviously " 6" can’t be parsed as well as "123 " can’t. It’s because of the spaces. But it can occure, that the String will look like "6" but actually it’s length will be larger than the number of digits you can see.

In this case I suggest using the debugger or at least System.out.println and print the length of the String you’re trying to parse. If it shows more than the number of digits, try passing stringToParse.trim() to the parsing method. If it won’t work, copy the whole string after the : and decode it using online decoder. It’ll give you codes of all characters.

There is also one case which I have found recently on StackOverflow, that you might see, that the input looks like a number e.g. "1.86" and it only contains those 4 characters but the error still exists. Remember, one can only parse integers with #Integer#parseInt#. For parsing decimal numbers, one should use Double#parseDouble.

Another situation is, when the number has many digits. It might be, that it’s too large or too small to fit int or long. You might want to try new BigDecimal(<str>).

Ad. 4.

Finally we come to the place in which we agree, that we can’t avoid situations when it’s user typing «abc» as a numeric string. Why? Because he can. In a lucky case, it’s because he’s a tester or simply a geek. In a bad case it’s the attacker.

What can I do now? Well, Java gives us try-catch you can do the following:

try {
    i = Integer.parseInt(myString);
} catch (NumberFormatException e) {
    e.printStackTrace();
    //somehow workout the issue with an improper input. It's up to your business logic.
}

The NumberFormatException is one of the most common errors in Java applications, along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g., int, float, double, long, short, char, or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. 

Even though the root cause is always something that cannot be converted into a number, there are many reasons and inputs due to which NumberFormatException occurs in Java applications.

Most of the time, I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons for java.lang.NumberFormatException in Java programs.

Having knowledge of these causes will help you to understand, analyze and solve this error in your Java application. In each case, you’ll see an error message, and then I’ll explain the reason behind it.

It’s difficult to cover all scenarios on which JVM throws this error, but I have tried to capture as many as possible here. If you find any other reasons or faced this error in your Java project due to anything mentioned below, then please share with us via comments.

10 common reasons for NumberFormatException 

Here are 10 reasons which I have seen causing NumberFormatException in Java application. If you have any reason which is not listed here, but you have seen them causing this error, feel free to add it.

1. Null Input Value

Since String is an object, it’s possible that it could be null, and if you pass a null String to a method like parseInt(), it will throw NumberFormatException because null is not numeric.

Integer.parseInt(null);
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)

You can see that the error message also contains the argument to parseInt(), which is null, and that’s the reason for this error. Thanks to JDK developers for printing the argument as well and a lesson to all Java developers who create their custom Exception class, always print the input which failed the process.  If you want to learn more about best practices, read Java Coding Guidelines.

2. Empty String

Another common reason of java.lang.NumberFormatException is an empty String value. Many developers think empty String is OK and parseInt() will return zero or something, but that’s not true. The parseInt(), or parseFloat() both will throw NumberFormat error as shown below:

Integer.parseInt("");
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)

Again you can see that this method has printed the input, which is an empty String and which caused the failure.

3. Alphanumeric Input

Another common reason for NumberFormatException is the alphanumeric input. No non-numeric letter other than + and is not permitted in the input string.

Short.parseShort("A1");
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "A1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Short.parseShort(Short.java:117)
at java.lang.Short.parseShort(Short.java:143)

You can see that our input contains «A,» which is not permitted. Hence it caused the error, but you should remember that A is a valid letter when you convert String to an integer in hexadecimal base. See these Java Coding Courses for beginners to learn more about data type conversion in Java.

4. Leading space

You won’t believe but leading, and trailing spaces are one of the major reasons for NumberFormatException in Java; you will think that input String » 123″ is Ok, but it’s not. It has a leading space in it.

Long.parseLong(" 123");
Exception in thread "main" java.lang.NumberFormatException: 
For input string: " 123"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:430)
at java.lang.Long.parseLong(Long.java:483)

Even though the parseLong() method is correctly printing the invalid input, it’s hard to spot the leading or trailing error in log files, particularly the trailing one. So, pay special attention to leading and trailing space while converting String to long in Java; if possible, use trim() before passing String to parseLong() method.

5. Trailing space

Similar to the above issue, trailing space is another main reason for numerous NumberFormatException in Java. A trailing white space is harder to spot than a leading white space, particularly in log files.

Long.parseLong("1001 ");
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "1001 "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

To avoid this error, you should trim() the input string before passing it to parse methods like the parseInt() or parseFloat().

6. Null String

We’ve already seen a scenario where the parseInt() method throws NumberFormatException if the input is null, but sometimes you will see an error message like Exception in thread «main» java.lang.NumberFormatException: «null» is different than the first scenario. 

In the first case, we have a null value; here we have a «null» String i.e., an initialized String object whose value is «null.» Since this is also not numeric, parseInt(), or parseFloat() will throw the NumberFormat exception as shown below.

Float.parseFloat("null");
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
at java.lang.Float.parseFloat(Float.java:452)

If you are not familiar with the concept of null in Java, please see these Java development courses for beginners on Medium.

7. Floating point String

This is a little bit different, even though «1.0» is a perfectly valid String i.e., it doesn’t contain any alphanumeric String, but if you try to convert it into integer values using parseInt(), parseShort(), or parseByte() it will throw NumberFormatException because «1.0» is a floating-point value and cannot be converted into integral one. These methods don’t cast. They just do the conversion.

Long.parseLong("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.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

So, be careful while converting floating-point String to numbers. They can only be converted to float or double, but not on integral types like byte, short, or int.

8. Out of range value

Another rare reason for java.lang.NumberFormatException is out-of-range value. For example, if you try to convert String «129» to a byte value, it will throw NumberFormatException because the maximum positive number byte can represent is 127. Clearly, 129 is out-of-range for a byte variable

Byte.parseByte("129");
Exception in thread "main" java.lang.NumberFormatException: 
Value out of range. Value:"129" Radix:10
at java.lang.Byte.parseByte(Byte.java:150)
at java.lang.Byte.parseByte(Byte.java:174)

If you are not familiar with data types and their range in Java, please see these free Java programming courses for more information.

9. Non-printable character

While working in the software industry, sometimes you face an issue where you think the computer is wrong, it has gone mad, the input String looks perfectly OK, but still, Java is throwing NumberFormatException, this happens, but at the end, you will realize that computer is always right.

For example, consider this error message:

java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

«1» is perfectly Ok for parseInt(), and it will run fine then why java.lang.NumberFormatException? It turns out that there was a non-printable character in front of 1, which was not displaying in the place where you are seeing. So, watch out for the non-printable character if you are facing a weird error.

10. Similar looking characters like 1 and l

This is the close cousin of earlier error. This time also our eye believes that input String is valid and thinks that the computer has gone mad, but it wasn’t. Only after spending hours did you realize that Java was right, the String you are trying to convert into a number was not numeric one «1» instead it was a small case letter L, i.e. «l». You can see it’s very subtle and not obvious from the naked eye unless you are really paying attention.

Integer.parseInt("l");
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "l"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)

From the error message, it looks like the error is for numeric String «1». So be careful with this.

Here is a nice slide to combine all these reasons into one, which you can share as well :

10 Reasons of java.lang.NumberFormatException in Java  - Solution

That’s all about 10 common reasons of java.lang.NumberFormatException and how to solve them. It’s one of those errors where you need to investigate more about data than code. You need to find the source of invalid data and correct it. In code, just make sure you catch the NumberFormatException whenever you convert a string to a number in Java. 

Other Java troubleshooting tutorials you may like to explore

  • How to fix «Error: Could not find or load main class» in Eclipse? (guide)
  • How to avoid ConcurrentModificationException in Java? (tutorial)
  • How to solve «could not create the Java virtual machine» error in Java? (solution)
  • How to fix «illegal start of expression» compile time error in Java? (tutorial)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 60.0 (solution)
  • Cause and solution of «class, interface, or enum expected» compiler error in Java? (fix)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory error (solution)
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
  • Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • How to solve «variable might not have initialized» compile time error in Java? (answer)
  • How to fix ‘javac’ is not recognized as an internal or external command (solution)
  • How to fix Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • How to solve java.lang.OutOfMemoryError: Java Heap Space in Eclipse, Tomcat? (solution)

Also, if you get input from the user, make sure you perform validation. Use Scanner if taking input from the command line and methods like the nextInt() to directly read integer instead of reading String and then parsing it to int again using parseInt() method, only to be greeted by NumberFormatExcpetion.

java.lang.NumberFormatException for input string is one of the most common exceptions java programmers face while doing the coding. This exception occurs when someone tries to convert a String into primitive data types such as int, float, double, long, byte, short, etc. It happens only when the String is not valid to be converted into primitive datatype.

Read Also: Exception Handling Interview Questions

The methods like Integer.parseInt(), Float.parseFloat(), Double.parseDouble() etc. throw java.lang.NumberFormatException when someone tries to convert an invalid String into number.

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "1";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
1

The above code is perfect and will not throw any error or exception. The String “1” was successfully converted into Integer 1 because the String was legal to be converted into numerical data.

Now, change the above code a little bit and let see what happens:

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "1A";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «1A»    

The above code will generate a java.lang.NumberFormatException because String “1A” was not a valid String for conversion into a primitive datatype.

What are the possible reasons for NumberFormatException?

These are the following possible reasons for NumberFormatException in Java:

1. Converting Null Value to Number

In Java, String containing null value can’t be converted into a primitive data type. For example, a null String can’t be converted into an int, float, double, long, short, or byte data type.

For example:

class JavaHungry
{
    public static void main(String args[])
    {
        String s = null;
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «null»
 

2. Empty String to Number

In Java, Empty String can’t be converted into a primitive data type. Any String of length 0 is referred  as an empty String in Java.

For example:

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «»

3. Alphanumeric String

Alphanumeric String (String which is a combination of alphabetic characters and numbers) cannot be converted into primitive data types.

For example:

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "AliveisAwesome2020";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «AliveisAwesome2020»
 

4. Leading or Trailing Spaces

Strings with leading or trailing spaces are not valid Strings for conversion into primitive data types. This is one of the most possible reasons for this exception.

For example:

public class JavaHungry
{
    public static void main(String args[])
    {
        // Trailing Space  
        String s = "123 ";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «123 «

5. Conversion of Floating Point String into Integer

Floating-point Strings such as «1.0» are not considered as a valid String for conversion into primitive data types such as int, long, short, etc. in java.

For example:

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "1.0";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «1.0»
 

6. Out of Range Value

A valid String can be converted into a primitive data type if and only if its numerical value lies within the range of that data type. For example, the range of byte is -128 to 127. So, if someone tries to convert “131” or “-129” to byte, java.lang.NumberFormatException will occur at runtime.

For example:

public class JavaHungry
{
    public static void main(String args[])
    {
        String s = "-129";
        byte i = Byte.parseByte(s);
        System.out.println(i);
    }
}

Output:
Exception in thread «main» java.lang.NumberFormatException: Value out of range. Value:»-129″ Radix:10
 

So, these were some common reasons for java.lang.NumberFormatException for the input string. We can handle this exception by keeping the above reasons in mind and avoiding them in our code. However, using a try-catch block is still a good choice to handle exceptions.

Reference:
NumberFormatException Oracle docs

Содержание

  1. 10 Reasons of java.lang.NumberFormatException in Java — Solution
  2. 10 common reasons for NumberFormatException
  3. 1. Null Input Value
  4. 2. Empty String
  5. 3. Alphanumeric Input
  6. 4. Leading space
  7. 5. Trailing space
  8. 6. Null String
  9. 7. Floating point String
  10. 8. Out of range value
  11. 9. Non-printable character
  12. 10. Similar looking characters like 1 and l
  13. Java Hungry
  14. [Solved] java.lang.NumberFormatException: For input string
  15. What are the possible reasons for NumberFormatException?
  16. 1. Converting Null Value to Number
  17. 2. Empty String to Number
  18. 3. Alphanumeric String
  19. 4. Leading or Trailing Spaces
  20. 5. Conversion of Floating Point String into Integer
  21. Понимание исключения NumberFormatException в Java
  22. 1. Введение
  23. 2. Причины исключения NumberFormatException
  24. 2.1. Нечисловые данные, передаваемые в конструктор
  25. 2.2. Анализ строк, содержащих нечисловые данные
  26. 2.3. Передача строк с посторонними символами
  27. 2.4. Форматы номеров для конкретных регионов
  28. 3. Передовой опыт
  29. 4. Вывод
  30. Java integer input exception
  31. Field Summary
  32. Constructor Summary
  33. Method Summary
  34. Methods inherited from class java.lang.Object
  35. Field Detail
  36. MIN_VALUE
  37. MAX_VALUE
  38. BYTES
  39. Constructor Detail
  40. Integer
  41. Integer
  42. Method Detail
  43. toString
  44. toUnsignedString
  45. toHexString
  46. toOctalString
  47. toBinaryString
  48. toString
  49. toUnsignedString
  50. parseInt
  51. parseInt
  52. parseUnsignedInt
  53. parseUnsignedInt
  54. valueOf
  55. valueOf
  56. valueOf
  57. byteValue
  58. shortValue
  59. intValue
  60. longValue
  61. floatValue
  62. doubleValue
  63. toString
  64. hashCode
  65. hashCode
  66. equals
  67. getInteger
  68. getInteger
  69. getInteger
  70. decode
  71. compareTo
  72. compare
  73. compareUnsigned
  74. toUnsignedLong
  75. divideUnsigned
  76. remainderUnsigned
  77. highestOneBit
  78. lowestOneBit
  79. numberOfLeadingZeros
  80. numberOfTrailingZeros
  81. bitCount
  82. rotateLeft
  83. rotateRight

10 Reasons of java.lang.NumberFormatException in Java — Solution

Most of the time, I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons for java.lang.NumberFormatException in Java programs.

Having knowledge of these causes will help you to understand, analyze and solve this error in your Java application. In each case, you’ll see an error message, and then I’ll explain the reason behind it.

It’s difficult to cover all scenarios on which JVM throws this error, but I have tried to capture as many as possible here. If you find any other reasons or faced this error in your Java project due to anything mentioned below, then please share with us via comments.

10 common reasons for NumberFormatException

Here are 10 reasons which I have seen causing NumberFormatException in Java application. If you have any reason which is not listed here, but you have seen them causing this error, feel free to add it.

1. Null Input Value

Since String is an object, it’s possible that it could be null, and if you pass a null String to a method like parseInt() , it will throw NumberFormatException because null is not numeric.

You can see that the error message also contains the argument to parseInt(), which is null, and that’s the reason for this error. Thanks to JDK developers for printing the argument as well and a lesson to all Java developers who create their custom Exception class, always print the input which failed the process. If you want to learn more about best practices, read Java Coding Guidelines.

2. Empty String

Another common reason of java.lang.NumberFormatException is an empty String value. Many developers think empty String is OK and parseInt() will return zero or something, but that’s not true. The parseInt() , or parseFloat() both will throw NumberFormat error as shown below:

Again you can see that this method has printed the input, which is an empty String and which caused the failure.

3. Alphanumeric Input

Another common reason for NumberFormatException is the alphanumeric input. No non-numeric letter other than + and — is not permitted in the input string.

You can see that our input contains «A,» which is not permitted. Hence it caused the error, but you should remember that A is a valid letter when you convert String to an integer in hexadecimal base. See these Java Coding Courses for beginners to learn more about data type conversion in Java.

4. Leading space

You won’t believe but leading, and trailing spaces are one of the major reasons for NumberFormatException in Java; you will think that input String » 123″ is Ok, but it’s not. It has a leading space in it.

Even though the parseLong() method is correctly printing the invalid input, it’s hard to spot the leading or trailing error in log files, particularly the trailing one. So, pay special attention to leading and trailing space while converting String to long in Java; if possible, use trim() before passing String to parseLong() method.

5. Trailing space

Similar to the above issue, trailing space is another main reason for numerous NumberFormatException in Java. A trailing white space is harder to spot than a leading white space, particularly in log files.

To avoid this error, you should trim() the input string before passing it to parse methods like the parseInt() or parseFloat() .

6. Null String

In the first case, we have a null value; here we have a «null» String i.e., an initialized String object whose value is «null.» Since this is also not numeric, parseInt(), or parseFloat() will throw the NumberFormat exception as shown below.

If you are not familiar with the concept of null in Java, please see these Java development courses for beginners on Medium.

7. Floating point String

This is a little bit different, even though «1.0» is a perfectly valid String i.e., it doesn’t contain any alphanumeric String, but if you try to convert it into integer values using parseInt() , parseShort(), or parseByte() it will throw NumberFormatException because «1.0» is a floating-point value and cannot be converted into integral one. These methods don’t cast. They just do the conversion.

So, be careful while converting floating-point String to numbers. They can only be converted to float or double, but not on integral types like byte, short, or int.

8. Out of range value

Another rare reason for java.lang.NumberFormatException is out-of-range value. For example, if you try to convert String «129» to a byte value, it will throw NumberFormatException because the maximum positive number byte can represent is 127. Clearly, 129 is out-of-range for a byte variable

If you are not familiar with data types and their range in Java, please see these free Java programming courses for more information.

9. Non-printable character

While working in the software industry, sometimes you face an issue where you think the computer is wrong, it has gone mad, the input String looks perfectly OK, but still, Java is throwing NumberFormatException , this happens, but at the end, you will realize that computer is always right.

For example, consider this error message:

«1» is perfectly Ok for parseInt(), and it will run fine then why java.lang.NumberFormatException ? It turns out that there was a non-printable character in front of 1, which was not displaying in the place where you are seeing. So, watch out for the non-printable character if you are facing a weird error.

10. Similar looking characters like 1 and l

This is the close cousin of earlier error. This time also our eye believes that input String is valid and thinks that the computer has gone mad, but it wasn’t. Only after spending hours did you realize that Java was right, the String you are trying to convert into a number was not numeric one «1» instead it was a small case letter L, i.e. «l» . You can see it’s very subtle and not obvious from the naked eye unless you are really paying attention.

From the error message, it looks like the error is for numeric String «1» . So be careful with this.

Here is a nice slide to combine all these reasons into one, which you can share as well :

Источник

Java Hungry

Java developers tutorials and coding.

[Solved] java.lang.NumberFormatException: For input string

java.lang.NumberFormatException for input string is one of the most common exceptions java programmers face while doing the coding. This exception occurs when someone tries to convert a String into primitive data types such as int, float, double, long, byte, short, etc. It happens only when the String is not valid to be converted into primitive datatype.

The methods like Integer.parseInt(), Float.parseFloat(), Double.parseDouble() etc. throw java.lang.NumberFormatException when someone tries to convert an invalid String into number.

The above code is perfect and will not throw any error or exception. The String “1” was successfully converted into Integer 1 because the String was legal to be converted into numerical data.

Now, change the above code a little bit and let see what happens:

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «1A»

The above code will generate a java.lang.NumberFormatException because String “1A” was not a valid String for conversion into a primitive datatype.

What are the possible reasons for NumberFormatException?

These are the following possible reasons for NumberFormatException in Java:

1. Converting Null Value to Number

In Java, String containing null value can’t be converted into a primitive data type. For example, a null String can’t be converted into an int, float, double, long, short, or byte data type.

2. Empty String to Number

In Java, Empty String can’t be converted into a primitive data type. Any String of length 0 is referred as an empty String in Java.

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «»

3. Alphanumeric String

Alphanumeric String (String which is a combination of alphabetic characters and numbers) cannot be converted into primitive data types.

4. Leading or Trailing Spaces

Strings with leading or trailing spaces are not valid Strings for conversion into primitive data types. This is one of the most possible reasons for this exception.

Output:
Exception in thread «main» java.lang.NumberFormatException: For input string: «123 «

5. Conversion of Floating Point String into Integer

Floating-point Strings such as «1.0» are not considered as a valid String for conversion into primitive data types such as int, long, short, etc. in java.

Источник

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

1. Введение

Java выдает NumberFormatException — непроверенное исключение — когда не может преобразовать String в числовой тип.

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

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

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

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

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

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

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

Оба этих оператора вызовут исключение NumberFormatException :

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

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

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

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

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

Если мы попробуем сделать такие же преобразования с помощью этих:

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

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

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

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

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

Мы можем исправить это с помощью небольших манипуляций со строками:

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

2.4. Форматы номеров для конкретных регионов

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

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

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

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

Давайте посмотрим на это в действии на примере Locale для Франции:

3. Передовой опыт

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

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

4. Вывод

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

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

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

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

Источник

Java integer input exception

In addition, this class provides several methods for converting an int to a String and a String to an int , as well as other constants and methods useful when dealing with an int .

Implementation note: The implementations of the «bit twiddling» methods (such as highestOneBit and numberOfTrailingZeros ) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).

Field Summary

Fields

Modifier and Type Field and Description
static int BYTES

Constructor Summary

Constructors

Constructor and Description
Integer (int value)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type Method and Description
static int bitCount (int i)

static int divideUnsigned (int dividend, int divisor) static int remainderUnsigned (int dividend, int divisor) static int rotateLeft (int i, int distance) static int rotateRight (int i, int distance)

Methods inherited from class java.lang.Object

Field Detail

MIN_VALUE

MAX_VALUE

BYTES

Constructor Detail

Integer

Integer

Method Detail

toString

If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.

If the first argument is negative, the first element of the result is the ASCII minus character ‘-‘ ( ‘u002D’ ). If the first argument is not negative, no sign character appears in the result.

The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:

toUnsignedString

If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.

Note that since the first argument is treated as an unsigned value, no leading sign character is printed.

If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character.

The behavior of radixes and the characters used as digits are the same as toString .

toHexString

The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0 s.

The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 16) .

If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:

toOctalString

The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0 s.

The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 8) .

If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as octal digits:

toBinaryString

The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0 s.

The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 2) .

If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters ‘0’ ( ‘u0030’ ) and ‘1’ ( ‘u0031’ ) are used as binary digits.

toString

toUnsignedString

parseInt

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ ( ‘u002D’ ) or plus sign ‘+’ ( ‘u002B’ ) provided that the string is longer than length 1.
  • The value represented by the string is not a value of type int .

parseInt

parseUnsignedInt

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
  • Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign ‘+’ ( ‘u002B’ ) provided that the string is longer than length 1.
  • The value represented by the string is larger than the largest unsigned int , 2 32 -1.

parseUnsignedInt

valueOf

In other words, this method returns an Integer object equal to the value of:

valueOf

In other words, this method returns an Integer object equal to the value of:

valueOf

byteValue

shortValue

intValue

longValue

floatValue

doubleValue

toString

hashCode

hashCode

equals

getInteger

The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.

If there is no property with the specified name, if the specified name is empty or null , or if the property does not have the correct numeric format, then null is returned.

In other words, this method returns an Integer object equal to the value of:

getInteger

The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.

The second argument is the default value. An Integer object that represents the value of the second argument is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .

In other words, this method returns an Integer object equal to the value of:

getInteger

The second argument is the default value. The default value is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .

decode

The sequence of characters following an optional sign and/or radix specifier (» 0x «, » 0X «, » # «, or leading zero) is parsed as by the Integer.parseInt method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign. No whitespace characters are permitted in the String .

compareTo

compare

compareUnsigned

toUnsignedLong

divideUnsigned

Note that in two’s complement arithmetic, the three other basic arithmetic operations of add, subtract, and multiply are bit-wise identical if the two operands are regarded as both being signed or both being unsigned. Therefore separate addUnsigned , etc. methods are not provided.

remainderUnsigned

highestOneBit

lowestOneBit

numberOfLeadingZeros

Note that this method is closely related to the logarithm base 2. For all positive int values x:

  • floor(log2(x)) = 31 — numberOfLeadingZeros(x)
  • ceil(log2(x)) = 32 — numberOfLeadingZeros(x — 1)

numberOfTrailingZeros

bitCount

rotateLeft

Note that left rotation with a negative distance is equivalent to right rotation: rotateLeft(val, -distance) == rotateRight(val, distance) . Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative: rotateLeft(val, distance) == rotateLeft(val, distance & 0x1F) .

rotateRight

Note that right rotation with a negative distance is equivalent to left rotation: rotateRight(val, -distance) == rotateLeft(val, distance) . Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative: rotateRight(val, distance) == rotateRight(val, distance & 0x1F) .

Источник

The NumberFormatException is the frequently occurred exception in Java applications like NullPointerException.

NumberFormatException is an unchecked exception that occurred we try to convert a String to a number type.

Many Java methods 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.

In this article, we will see how the NumberFormatException exception occurred and ways to avoid NumberFormatExcpetion in Java.

Null String

Some times we see the Exception in thread «main» java.lang.NumberFormatException: «null». In the first case, In this, we have a «null» String i.e. an initialized String object whose value is «null». Since this is also not numeric, parseInt(), or parseFloat() will throw the NumberFormat exception as shown below.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForNull{

     public static void main(String []args){
        float ft =  Float.parseFloat("null");
        System.out.println(ft);
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at NumberFormatForNull.main(NumberFormatForNull.java:4)
 

Converting Float to String

In this case «1.0» is perfectly valid String i.e. it doesn’t contain any alphanumeric String. If you try to convert it into integer values using parseInt(), parseShort(), or parseByte() it will throw NumberFormatException because «1.0» is a floating-point value and cannot be converted into integral one.

These methods don’t cast they just do the conversion.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForFloat {

     public static void main(String []args){
         
        long lg = Long.parseLong("1.0");
        
        System.out.println(lg );
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.parseLong(Long.java:631)
	at NumberFormatForFloat.main(NumberFormatForFloat.java:6)
 

Convert String to Out of range values

Suppose we have string «130» to a byte, It throws NumberFormatException as the given type byte has rage is 128, which is exceeded by us.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForByte {

     public static void main(String []args){
         
        byte bt = Byte.parseByte("129");
        
        System.out.println(bt);
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10
	at java.lang.Byte.parseByte(Byte.java:151)
	at java.lang.Byte.parseByte(Byte.java:175)
	at NumberFormatForByte.main(NumberFormatForByte.java:6)
 

Leading and Trailing space in String

This is a common error when we read values from the properties files and there are leading and trailing spaces present in the string.

If we want to convert » 128″ into an integer, it will throw exception java.lang.NumberFormatException.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForLeadingSpace {

     public static void main(String []args){
         
     int thumbnailLength = Integer.parseInt(" 128");
        
     System.out.println(thumbnailLength);
     }
}
Exception in thread "main" java.lang.NumberFormatException: For input string: " 128"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:569)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.javacodestuffs.core.exception.handling.NumberFormatForLeadingSpace.main(NumberFormatForLeadingSpace.java:6)
 

For Trailing Spaces


 package com.javacodestuffs.core.exception.handling;
public class NumberFormatForTrailingSpace {

     public static void main(String []args){
         
     int thumbnailHeight = Integer.parseInt("128  ");
        
     System.out.println(thumbnailHeight);
     }
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "128  "
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.javacodestuffs.core.exception.handling.NumberFormatForTrailingSpace.main(NumberFormatForTrailingSpace.java:6)

Alphanumeric Input

This is a common mistake by the programmer for the alphanumeric input. No non-numeric letter other than + and — is not permitted in the input string.
It will throw an exception.


package com.javacodestuffs.core.exception.handling;

public class NumberFormatForAlphanumeric {

     public static void main(String []args){
         
     short sh = Short.parseShort("B6");
         
     System.out.println(sh);
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "B6"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Short.parseShort(Short.java:118)
	at java.lang.Short.parseShort(Short.java:144)
	at com.javacodestuffs.core.exception.handling.NumberFormatForAlphanumeric.main(NumberFormatForAlphanumeric.java:6)

Empty String

This is the most common mistakes that happened from the programmer to convert an empty string to numeric or float values.

The parseInt(),parseFloat() …etc will throw NumberFormatException.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForAlphanumericEmptyString {

	public static void main(String[] args) {

		int value = Integer.parseInt("");

		System.out.println(value);
	}
}
output:
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:592)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.javacodestuffs.core.exception.handling.NumberFormatForAlphanumericEmptyString.main(NumberFormatForAlphanumericEmptyString.java:6)

null values

This will happens when we pass null to a method like parseInt or parseFloat.It mostly occurs when we expect return values from some other methods and forgot to put a null check before converting it to our required type.


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForNullvalues {

     public static void main(String []args){
         
     int value = Integer.parseInt(null);
         
     System.out.println(value);
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: null
	at java.lang.Integer.parseInt(Integer.java:542)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.javacodestuffs.core.exception.handling.NumberFormatForNullvalues.main(NumberFormatForNullvalues.java:6)

characters e.g 1 and l

This is another mistake by the programmer. Consider or typo «1» as «l».


package com.javacodestuffs.core.exception.handling;
public class NumberFormatForTypo {

     public static void main(String []args){
         
     int value = Integer.parseInt("l");
         
     System.out.println(value);
     }
}
output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "l"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.javacodestuffs.core.exception.handling.NumberFormatForTypo.main(NumberFormatForTypo.java:6)

Best Practices to avoid java.lang.NumberFormatException

1). Don’t try to convert alphabetic or special characters into numbers – the Java Number
API cannot do that.

2). We may want to validate an input string using regular expressions and throw the exception for
the invalid characters.

3). We can sanitize input against foreseeable known issues with methods like trim() and replaceAll().

4). In some cases, special characters in input may be valid. So, we do special processing for
that, using NumberFormat.

5). validate the input before converting it to antother data types.

6). Checks whether the String a valid Java number.

7). Determine if a string is Int or Float and to represent in longer format.


String cost = "";
if (cost !=null && !"".equals(cost) ){
        try {
           Integer intCost = Integer.parseInt(cost);
           List<Book> books = bookService.findBooksCheaperThan(intCost);  
        } catch (NumberFormatException e) {
           System.out.println("Cost is not a number.");
           System.out.println(e.getMessage());
        }
    }  

Post/Questions related to Java lang number format exception

How to resolve number format exception in java?

How to resolve class cast exception in java?

How to fix «Error: Could not find or load main class» in Eclipse?

Ways to avoid ConcurrentModificationException in Java?

How to solve «could not create the Java virtual machine» error in Java?

How to fix «illegal start of expression» compile-time error in Java?

Cause and solution of «class, interface, or enum expected» compiler error in Java?

How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error?

How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver?

Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java?

java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener

How to solve «variable might not have initialized» compile-time error in Java?

How to fix ‘javac’ is not recognized as an internal or external command

How to solve java.lang.OutOfMemoryError: Java Heap Space in Eclipse, Tomcat?

Best Practices to Handle Exceptions in Java

In this article, we have seen the  Java lang number format exception with examples. All source code in the tutorial can be found in the GitHub repository.

Вопрос:

Я получаю эту ошибку, когда запускаю следующий код и вводя 5×5 для размера. Не знаете почему?

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

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)"

Вот мой код

    import java.util.Scanner;

public class CheckerBoard {

public static void main(String [] args){

Scanner userInput = new Scanner(System.in);

System.out.println("What two colors would you like your board to be?");

String colorOne = userInput.next();
String colorTwo = userInput.next();

do {
System.out.println("How big should the checker board be? (Square sizes only please)" + "n"
+ "Please enter it like 4x4 with whatever numbers you choose.");

String boardSize = userInput.next();

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));
System.out.println(boardSize.indexOf("x"));
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));
System.out.println(intOne);

} while(false);
}
}

//keep in mind that this program is not done yet, this is just a current issue I am having atm.

Лучший ответ:

Проблема здесь:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));

Вы берете подстроку от x до length - 1. Вы должны перейти от x к length потому что substring не включает второй индекс.

Итак, вы получили ошибку на 5x5 потому что после x есть только один символ. Таким образом, вы пытались parseInt пустую строку. У вас не было исключения на 10x10, но вы использовали только 10x1.

Таким образом, вы должны изменить эту строку следующим образом:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

Ответ №1

Я считаю, что более безопасный способ сделать это – раскол на x

String boardSize = userInput.next();
String[] split = boardSize.split("x");
int intOne = Integer.parseInt(split[0]);
int intTwo = Integer.parseInt(split[1]);

Очевидно, санируйте для BAD INPUT!

Ответ №2

В вашем коде не учитывается, что строка boardSize может быть пуста, когда выполняется строка;

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));

Когда вы выполняете “indexOf”, ища то, чего не существует, вы получите -1 назад, что является недопустимым как аргумент вашей подстроки.

Ответ №3

Вы пробовали это?

        int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

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

Ответ №4

+ Изменить
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));
в
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));
Помните, что второй индекс, переданный в String.substring, не будет включен в возвращаемое значение.

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at HelloWorld.main(HelloWorld.java:169)

Эти ошибки продолжают появляться, когда я запускаю свой код по сравнению с нашим примером ввода. Нам дается документ с полигонами и приходится использовать алгоритм kruskal и строить минимальное остовное дерево, чтобы найти кратчайшее расстояние до каждого острова без создания цикла. Если кто-то может помочь или дать совет о том, как избавиться от этих ошибок, это было бы здорово! Я не понимаю, как может быть numberformatexception в строке «»….

import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;

public class HelloWorld {
static class Point {
int x = 0;
int y = 0;

public Point(int x, int y) {
this.x = x;
this.y = y;
}

public String toString() {
return "(x: " + x + " y: " + y + ")";
}
}

static class Polygon {
int numberOfVertices = 0;
ArrayList<Point> points = new ArrayList<Point>();

public Polygon(int numberOfVertices, ArrayList<Point> points) {
this.numberOfVertices = numberOfVertices;
this.points = points;
}

public String toString() {
StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < points.size(); i++) {
Point point = this.points.get(i);
stringBuilder.append(point);
}

return stringBuilder.toString();
}
}

static class PQItem implements Comparable<PQItem> {
int node1;
int node2;
double edge;

public PQItem(int node1, int node2, double edge) {
this.node1 = node1;
this.node2 = node2;
this.edge = edge;
}

public int compareTo(PQItem T) {
if (edge - T.edge < 0)
return 1;
else if (edge - T.edge > 0)
return -1;
else
return 0;
}

}

public static void BuildMinimalSpanningTree(int numberOfIslands, ArrayList<Polygon> polygons) {
PriorityQueue q = new PriorityQueue((numberOfIslands * numberOfIslands) / 2);
PQItem Temp;
int[] CheckPad = new int[numberOfIslands];
int FootPrint = 0;
int counter = 0;
double length = 0;

for (int i = 0; i < polygons.size(); i++)
for (int j = 0; j < polygons.size(); j++) {
Temp = new PQItem(i, j, ShortestDistance(polygons.get(i), polygons.get(j)));
}

for (int i = 0; i < polygons.size(); i++)
CheckPad[i] = -1 - i;
while (counter < polygons.size() - 1) {
Temp = (PQItem) q.Remove();
for (int i = 0; i < polygons.size(); i++)
for (int j = 0; j < polygons.size(); j++)
if (CheckPad[Temp.node1] != CheckPad[Temp.node2]) {
if (CheckPad[Temp.node1] < 0 && CheckPad[Temp.node2] < 0) {
CheckPad[Temp.node1] = FootPrint;
CheckPad[Temp.node2] = FootPrint;
FootPrint = FootPrint + 1;
}

else if (CheckPad[Temp.node1] < 0) {
CheckPad[Temp.node1] = CheckPad[Temp.node2];
}

else if (CheckPad[Temp.node2] < 0) {
CheckPad[Temp.node2] = CheckPad[Temp.node1];
}

else {
if (CheckPad[Temp.node1] < CheckPad[Temp.node2]) {
for (i = 0; i < polygons.size(); i++) {
if (CheckPad[i] == CheckPad[Temp.node2])
CheckPad[i] = CheckPad[Temp.node2];
else
for (j = 0; j < polygons.size(); j++)
if (CheckPad[j] == CheckPad[Temp.node2])
CheckPad[j] = CheckPad[Temp.node2];
}
}
System.out.println(Temp.edge);
length += Temp.edge;
counter++;
}
}
}

}

static double ShortestDistance(Polygon polygon1, Polygon polygon2) {
double shortestdistance = 0;
double Temporary = 0;
for (int i = 0; i < polygon1.numberOfVertices; i++)
for (int j = 0; j < polygon2.numberOfVertices; j++) {
Temporary = Math.pow(polygon1.points.get(i).x - polygon2.points.get(j).x, 2)
+ Math.pow(polygon1.points.get(i).y - polygon2.points.get(j).y, 2);
if (Temporary < shortestdistance)
shortestdistance = Temporary;
}
return Math.sqrt(shortestdistance);

}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the name of the file");
File file = new File(scanner.nextLine());
try {
Scanner fileScanner = new Scanner(file);

int numberOfIslands = Integer.parseInt(fileScanner.nextLine());
ArrayList<Polygon> polygons = new ArrayList<Polygon>();

while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String[] numbers = line.split(" ");
ArrayList<Point> points = new ArrayList<Point>();
// PQItem NewItem = new PQItem(Node1, Node2, edge);
// info.Insert(NewItem);

for (int i = 1; i < numbers.length; i += 2) {
Point point = new Point(Integer.parseInt(numbers[i]), Integer.parseInt(numbers[(i + 1)]));

points.add(point);
}
// build tree

Polygon polygon = new Polygon(points.size(), points);

polygons.add(polygon);
// BuildMinSpanTree(numberOfIslands, polygons);

}

for (int i = 0; i < polygons.size(); i++) {
Polygon polygon = polygons.get(i);
System.out.println(polygon);
}

int minimalInterconnect = 0;
int totalLength = 0;

System.out.printf("The minimal interconnect consists of %d bridges with a total length of %d",
minimalInterconnect, totalLength);
} catch (IOException e) {
System.out.println(e);
}
}

ЗДЕСЬ ПРОГРАММА ОБРАЗЦА 3 4 0 0 0 1 1 1 1 0 4 2 0 2 1 3 1 3 0 3 4 0 5 0 5 1

public class PriorityQueue {
private Comparable[] HeapArray;
int Last, Limit;

PriorityQueue

public PriorityQueue(int Capacity) {
HeapArray = new Comparable[Capacity + 1];
Last = 0;
Limit = Capacity;
return;
}
// end constructor

public PriorityQueue() {
HeapArray = new Comparable[101];
Last = 0;
Limit = 100;
return;
}
// end constructor

public void Insert(Comparable PQI) {
if (Last == Limit) {
System.out.println("Priority Queue Overflow!");
System.exit(0);
}
// end if

HeapArray[++Last] = PQI;
this.UpHeap(Last);
return;
}
// end public method Insert

private void UpHeap(int k) {
Comparable V;

V = HeapArray[k];

while (k > 1 && HeapArray[k / 2].compareTo(V) < 0) {
HeapArray[k] = HeapArray[k / 2];
k = k / 2;
}
// end while

HeapArray[k] = V;
return;
}
// end private method UpHeap

public Comparable Remove() {
Comparable PQI;

if (Last == 0) {
System.out.println("Priority Queue Underflow!");
System.exit(0);
}
// end if

PQI = HeapArray[1];
HeapArray[1] = HeapArray[Last--];
this.DownHeap(1);
return PQI;
}
// end public method Remove

private void DownHeap(int k) {
Comparable V;
int j;

V = HeapArray[k];

while (k <= Last / 2) {
j = k + k;

if (j < Last && HeapArray[j].compareTo(HeapArray[j + 1]) < 0)
j++;
// end if

if (V.compareTo(HeapArray[j]) >= 0)
break;
// end if

HeapArray[k] = HeapArray[j];
k = j;
}
// end while

HeapArray[k] = V;
return;
}
// end private method DownHeap

public boolean IsEmpty() {
if (Last == 0)
return true;
else
return false;
// end if
}
// end public method IsEmpty

public boolean IsFull() {
if (Last == Limit)
return true;
else
return false;
// end if
}
// end public method IsFull

public int Length() {
return Last;
}
// end public method Length

}//end class PriorityQueue

  • For honor произошла ошибка невозможно запустить игру 05020000
  • Ford focus 2 ошибка p0700
  • Football manager ошибка crash dump
  • Ford focus ошибка p0460
  • For honor ошибка присоединения к сессии 0004000029