Search code examples
javavisual-studioexceptionnumberformatexception

Java Number Exception at string input from buffereader


import java.util.*;
import java.io.*;
import java.lang.*;

class Ex
{ 
    public static void main (String[] args) throws IOException
     {
        BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
        int a,b,n,c;
        n=Integer.parseInt(br.readLine());
        for(int i=1;i<=n;i++) 
        {   
            try
            { 
                a=Integer.parseInt(br.readLine());
                b=Integer.parseInt(br.readLine());
                try
                {
                    c=a/b;
                    System.out.println(c);
                }
                catch (ArithmeticException e)
                {
                    System.out.println(e);
                } 
            }    
            catch (InputMismatchException m) 
            {
                System.out.println(m);
            }       
        } 
    }
}

The above mentioned is my Code which I'm trying to run and below is the input_file.txt

4 
10
3
10
Hello
10
2
23.323
0.0

and this is the error which I get.

Exception in thread "main" java.lang.NumberFormatException: For input string: "4 "
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:580)
        at java.lang.Integer.parseInt(Integer.java:615)
        at Ex.main(Ex.java:11)

Solution

  • I think you have entered the number 4 with space. Please check your input.

    For input string: "4 "

    To avoid it you can add trim function as below

    Integer.parseInt(br.readLine().trim());