Search code examples
javajava.util.scannerbufferedreadernumberformatexception

Java Number Format Exception


I was solving aquestion on CodeChef platform when I faced a NumberFormatException.

First I used Scanner for handling the inputs, then BufferedReader. But none of them worked!

Here is my code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Practise {

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());

        while(t > 0) {
            String s = br.readLine();
            ArrayList<String> al = new ArrayList<>();
            int i = 0;

            while(i < s.length()) {
                String temp = "";
                while(s.charAt(i) != ' '){
                    temp += s.charAt(i);
                    i++;
                    if(i >= s.length()) {
                        break;
                    }
                }
                al.add(temp);
                i++;
            }

            if(al.contains("not")) {
                System.out.println("Real Fancy");
            } else {
                System.out.println("regularly Fancy");
            }

            t--;
        } 
    }
}

What could the problem be?

Input -->The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. -->The first and only line of each test case contains a single string S denoting a quote.

The Exception message i am getting-

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 Practise.main(Main.java:11)

Solution

  • Documentation:

    * 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.
    

    The exception will be thrown at the line int t = Integer.parseInt(br.readLine());. The reason why the exception will be thrown there is that the input that you read there isn't a Number. If it is a number + a String or something else it will throw the NumberFormatException.

    Example input 1235a

    This will throw an exception with the following message:

    java.lang.NumberFormatException: For input string: "1235a"

    So you should debug what the input there is.