OCP Question 19, Explanation

Given the code fragment:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter your score: ");
    //line 1
}

Which code fragment, when inserted at line 1, enables the code to read the user’s score?

A. int score = Integer.parseInt(br.readLine());
B. int score = br.read();
C. int score = br.nextInt();
D. int score = Integer.parseInt(br.next());

 

The correct answer is A.

This is actually an old way of inputting data, that is, by using Readers instead of the newer java.io.Console class. The BufferedReader’s read() method reads in just a single character, which makes option B incorrect. Option C’s nextInt() method belongs to Scanner rather that BufferedReader, and throws a comperr. As for option D, it is also syntactically invalid because BufferedReader doesn’t have a next() method, which is again defined in Scanner.

The correct option A reads a complete line of text from the standard input and returns a String, that’s why we needed to parse the read-in data.

Leave Comment

Your email address will not be published. Required fields are marked *