Search code examples
javaruntimeexception

why am i getting an error [Exception in thread "main" java.lang.NumberFormatException: For input string: "3"] in line 7 of my code?


So i was solving a question in competitive programming where i had to take these numbers as input...

3 
40 40 100
45 45 90
180 1 1

and here's my code:

package CP;
import java.io.*;
import java.util.*;
class Test {
    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){
            StringTokenizer s=new StringTokenizer(br.readLine());
            int a=Integer.parseInt(s.nextToken());
            int b=Integer.parseInt(s.nextToken());
            int c=Integer.parseInt(s.nextToken());
            if(a+b+c==180) System.out.println("YES");
            else System.out.println("NO");
        }
        br.close();
    }
}

so this code works fine when i take inputs line by line. but when i take all the lines as input at a time it shows [Exception in thread "main" java.lang.NumberFormatException: For input string: "3"] in line 7. why is this happening?


Solution

  • There is a space after the 3 in the input. This causes the Integer.parseInt(String) to fail. Trimming the line of input should suffice to solve your issue.

    int t = Integer.parseInt(br.readLine().trim());