Search code examples
javajava.util.scannerbufferedreader

BufferedReader giving non-zero exit code


Problem A simple programming question, involves reading a number N, T times from console and perform simple calculation on it.

Constraints:

1 ≤ T ≤ 1000

2 ≤ N ≤ 100000000

As BufferedReader is usually faster than Scanner, I used it but the program exited with Non-Zero Exit code whereas using Scanner resolved the issue.

Since both work fine on my computer, I suspect this is a memory issue.

Questions:

  1. Is my assumption that BufferedReader is faster than Scanner correct?
  2. Does BufferedReader use more memory? If yes, is it the reason for the error?

Code:

Using BufferedReader, throws error

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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        for (int i=0; i<T; i++) {
            int N = Integer.parseInt(br.readLine());
            int res = (N/2)+1;
            System.out.println(res);
        }
        br.close();
    }
}

The code using Scanner that returned correct output:

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException{
        Scanner sc = new Scanner(System.in);
        int T = Integer.parseInt(sc.nextLine());
        for (int i=0; i<T; i++) {
            int N = Integer.parseInt(sc.nextLine());
            int res = (N/2)+1;
            System.out.println(res);
        }
        sc.close();
    }
}

Solution

    1. As of JDK 7, BufferedReader uses a bigger buffer than Scanner (I think 8192c vs 1024c), so yes it uses more memory, and can make for a faster runtime on large inputs.
    2. This might be the source of your problem (or it might be that whoever wrote the tests for this problem has something wrong), since I tested your BufferedReader code myself and cannot see any problems with it.