Reputation: 2334
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:
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();
}
}
Upvotes: 7
Views: 1886
Reputation: 29
I had the same error you're having(an error on the BufferedReader
). It's because you forgot to put the BufferedReader
in a try catch block. I also had the throws IOException
after the main funtion but that's not enough. So it's not a memory issue.
The correct code could be something like this:
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 = null;
try {
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);
}catch(Exception e) {
e.printStackTrace();
}finally{
try{
br.close();
}catch ( Exception e){
e.printStackTrace();
}
} // end of try catch
}
}
Good Luck!
Upvotes: -1
Reputation: 1874
Upvotes: 3
Reputation: 311054
Is my assumption that BufferedReader is faster than Scanner correct?
Not in this case, as the speed of your program is limited by how fast you can type. Compared to that, any difference between Scanner and BufferedReader is insignificant.
Does BufferedReader use more memory?
It isn't specified.
If yes, is it the reason for the error?
Is it the reason for what error? As you didn't post the error you're getting, this question is unanswerable. However I don't see any reason to believe you have a memory problem.
Upvotes: 1