Programmers learn & share
0 votes
127 views

Problem :

I am getting bellow error when I try to use Integer.parseInt() with a single char

exception in thread "main" java.lang.numberformatexception: for input string: "s"

by (6.9k points)  
edited by | 127 views

2 Answers

0 votes

Solution:

To parse any string to a number you should have valid number into the string.

But your S is not a number.

String s = "s"; 
System.out.println((char) Integer.parseInt(s));

It should be something like bellow code:

String s = "400";
System.out.println((char) Integer.parseInt(s));
by (36.1k points)  
edited by
0 votes

Solution:

Reason behind this issue:

The NumberFormatException is one of the most common errors in Java application 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 which cannot be converted into a number, there are many reasons and input due to which NumberFormatException occurs in Java application. 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 of java.lang.NumberFormatException in Java programs.

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.

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

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

 

 

by (11.2k points)  
edited ago by
2,227 questions
2,734 answers
59 comments
241 users