Skip to content

NumberFormatException Example

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.

An simple example:

public class SummationExample {
    public static void main(String args[]){
        int sum = 0;
        for(String arg: args){
            System.out.println("+" + arg);
            sum += Integer.parseInt(arg);
        }
        System.out.println("= " + sum);
    }
}

$ javac SummationExample.java
$ java SummationExample 1 2 3 4 5
+1
+2
+3
+4
+5
= 15

but

$ java SummationExample 1 2 3 4 five
+1
+2
+3
+4
+five
Exception in thread “main” java.lang.NumberFormatException: For input string: “five”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at SummationExample.main(SummationExample.java:6)

So

public class SummationExample {
    public static void main(String args[]){
        int sum = 0;
        for(String arg: args){
            try {
                sum += Integer.parseInt(arg);
                System.out.println("+" + arg);
            } catch (NumberFormatException e) {
                // nothing
            }
        }
        System.out.println("= " + sum);
    }
}

now

$ javac BetterSummationExample.java
$ java BetterSummationExample 1 2 3 4 5
+1
+2
+3
+4
+5
= 15

and also

$ java BetterSummationExample 1 2 3 4 five
+1
+2
+3
+4
= 10

Java Duke animated gif waving

Published inenglish

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *