Java SE 8 Programmer II Exam: Code Fragment to Read GDP from User

Java SE 8 Programmer II Exam: Code Fragment to Read GDP from User

Question

Given the code fragment: public static void main (String [ ] args) throws IOException{ BufferedReader br = new BufferedReader (new InputStremReader (System.in)); System.out.print ("Enter GDP: "); //line 1 } Which code fragment, when inserted at line 1, enables the code to read the GDP from the user?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

In the given code fragment, an instance of the BufferedReader class is created to read input from the user through the console. The BufferedReader is initialized with an InputStreamReader, which in turn takes System.in as input to read data from the console.

To read the GDP from the user, we need to use one of the methods of the BufferedReader class. The BufferedReader class provides several methods to read different types of data, including strings, integers, and characters.

Option A: int GDP = Integer.parseInt(br.readLine()); This option reads a line of text from the console using the readLine() method of the BufferedReader class and then converts it to an integer using the parseInt() method of the Integer class. This option is correct because it reads the entire line of text entered by the user, ensuring that all input is captured as a single value.

Option B: int GDP = br.read(); This option reads a single character from the console using the read() method of the BufferedReader class. This option is incorrect because it only reads a single character, and the GDP entered by the user may be more than one character.

Option C: int GDP = br.nextInt(); This option reads an integer value from the console using the nextInt() method of the BufferedReader class. This option is incorrect because it only reads an integer value and does not handle any other input that may be entered by the user.

Option D: int GDP = Integer.parseInt(br.next()); This option reads a single token from the console using the next() method of the BufferedReader class and then converts it to an integer using the parseInt() method of the Integer class. This option is incorrect because it only reads a single token and does not handle any other input that may be entered by the user.

Therefore, the correct answer is A. int GDP = Integer.parseInt(br.readLine());.