Search code examples
javasystem.in

NumberFormatException when reading from System.in


I am getting these exception while running the code

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 Ideone.main(Main.java:22)

I am new at java and unable to resolve this error. Please help ! Here is my code ->

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


class etest {
    public static void main (String[] args) throws java.lang.Exception{
        int n,k;
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        k = in.nextInt();
        BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
        //StringTokenizer token = new StringTokenizer(input.readLine());
        int total=0;
        int values[] = new int[n];
        for(int i =0; i<n; i++) {
            values[i] = Integer.parseInt(input.readLine());
            if ((values[i]%k)==0) {
                total++ ;
            }
            input.close();
        }
        System.out.println(total);
    }
}

I am using the following input sample to run the program. Thank you so much for any help!

7 3
1
51
966369
7
9
999996
11

Solution

  • your program has too many errors :

    You can change your code as below

    public static void main(String[] args) throws java.lang.Exception {
        int n, k;
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        k = in.nextInt();
        int total = 0;
        int values[] = new int[n];
        for (int i = 0; i < n; i++) {
            values[i] = in.nextInt();
            if ((values[i] % k) == 0) {
                total++;
            }
        }
        System.out.println(total);
    }
    

    1) you should not close BufferedReader it will automatically close input stream also.

    2) you don't need Scanner and BufferedReader at the same time. your solution can use any one of them.

    3) better to use try-catch while using Integer.parseInt(String str);

    if you want to go with BufferedReader then you need to change your code as

    public static void main(String[] args) throws java.lang.Exception {
        int n, k;
    
    
        BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
        String str[]= input.readLine().split(" ");
        n = Integer.parseInt(str[0]);
        k = Integer.parseInt(str[1]);
        int total = 0;
        int values[] = new int[n];
        for (int i = 0; i < n; i++) {
            values[i]=Integer.parseInt(input.readLine());
            if ((values[i] % k) == 0) {
                total++;
            }
        }
        System.out.println(total);
    }