javaCoderMakeSimple
javaCoderMakeSimple

Reputation: 69

Why i am getting a Number FormatException?

I made a program on the code chef.I am getting a correct output on my eclipse ide and when i submitted it the output shown on CodeChef ide is :

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 Prog1.stop(Main.java:16)
at Prog1.main(Main.java:50)

Here is the question Link:https://www.codechef.com/problems/TEST

Here is my solution to the problem: //life universe and EveryThing

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Prog1 
{
 public static void stop() throws IOException
 {

   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   String s1=br.readLine();
   int x=Integer.parseInt(s1);
   int ar[]=new int[x];
   int k=0;
    for(int i=0;i<x;i++)
     {
       BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
       String s2=br1.readLine();
       int p=Integer.parseInt(s2);
       ar[k++]=p;
     }
   for(int m=0;m<x;m++)
    {
       System.out.println(ar[m]);
    }
   for(int y=0;y<x;)
    {
        if(ar[y]!=42)
        {
          System.out.println(ar[y]);
          y++;
        }
        else
        {
          break;
        }

    }

}
 public static void main(String s[]) throws IOException
 {
 stop();
 }
}

Upvotes: 1

Views: 4452

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500525

The immediate cause is that you're passing null into Integer.parseInt. Next you need to work out why that's happening...

You're creating a new BufferedReader wrapping System.in on each iteration... that's likely to be reading more than just a single line, which means some of the lines of input are effectively being swallowed.

Just create one BufferedReader at the start, and use that for the whole program. You could also check whether the return value for readLine is null, but as that would indicate invalid data it's not awful to just let that throw in the way it already is doing...

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

Cause:

You are doing Integer.parseInt(). That causes exception for non valid strings and nulls etc ..

Solution:

1) Have a null check

2) Try=Catch it and do necessary in catch.

Upvotes: 2

Rustam
Rustam

Reputation: 6515

first do a check if(s1!=null) then int x=Integer.parseInt(s1); use exception handling concept try catch.

            try{
                   if(s1!=null){
                       int x=Integer.parseInt(s1);
                   }
               }catch(NumberFormatException e){

               }

Upvotes: 1

Related Questions