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();
}
}
exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.
The read() method of a Java BufferedReader returns an int which contains the char value of the next character read. If the read() method returns -1, there is no more data to read in the BufferedReader , and it can be closed. That is, -1 as int value, not -1 as byte or char value.
BufferedReader input = new BufferedReader (new InputStreamReader (System.in)); Once we have created a BufferedReader we can use its method readLine() to read one line of characters at a time from the keyboard and store it as a String object. String inputString = input. readLine();
The buffered reader is linked with the input.FileReader file = new FileReader("input. txt"); BufferedReader input = new BufferedReader(file); Here, we have used the read() method to read an array of characters from the internal buffer of the buffered reader.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With