Problem Simple programming question involves reading the number N, T times from the console and performing simple calculations on it.
Limitations:
1 β€ T β€ 1000
2 β€ N β€ 100000000
Since BufferedReader is usually faster than a scanner, I used it, but the program exited Non-Zero Exit code, while using Scanner solved the problem.
Since both work fine on my computer, I suspect this is a memory issue.
Questions:
- I believe BufferedReader is faster than a scanner?
- Does BufferedReader use more memory? If so, is that the cause of the error?
The code:
Using BufferedReader causes an 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(); } }
Code using a scanner that returned the 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(); } }
java java.util.scanner bufferedreader
Rishi dua
source share