Add to Google Reader or Homepage

Exception in thread "main" java.lang.NumberFormatException

Number FormatException:

The Number Format Exception is thrown when the program tries to convert a string to any of the numeric types for which there is no appropriate number format available.This type of exception is usually caused by the type casting statements or the parsing statements.

Look at the program below to understand the NumberFormatException in detail.

Program:


import java.io.*;
import java.lang.*;
import java.util.*;
public class Illegalarg1
{
public static void main(String args[])throws IllegalArgumentException
{
String test="HELLO";
char in;
String index=null;
System.out.println("Enter the index:");
Scanner br =new Scanner(new InputStreamReader(System.in));
index = br.nextLine();

in= test.charAt(Integer.parseInt(index));
System.out.println("The char at the specified index is:"+in);
}
}

Error:

Enter the index:
y
Exception in thread "main" java.lang.NumberFormatException: For input string: "y
"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at Illegalarg1.main(Illegalarg1.java:15)

In this program i have tried to read the input from the user as string and converted it to an integer.Since we can read numbers as characters i used this method.But when the users tried to give the characters, such as alphabets or some other strings as input then this error would be thrown.

This type of exceptions can be resolved by using the exception handling mechanism to notify the user that the input given is incorrect or notify the programmer about the error so that he or she would make necessary changes.

This type of exceptions can also be eliminated by using strings that has a legitimate value for its corresponding numeric types.Note that even though we read the input as string the integer type values can be converted into an integer and  the double values can be converted into double values using the appropriate parser methods.


0 comments:

Post a Comment

 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top