Analyze the following code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 100000; i++) {
Scanner input = new Scanner(System.in);
sum += input.nextInt();
}
}
}
a. The program does not compile because the Scanner input = new Scanner(System.in); statement is inside the loop.
b. The program compiles, but does not run because the Scanner input = new Scanner(System.in); statement is inside the loop.
c. The program compiles and runs, but it is not efficient and unnecessary to execute the Scanner input = new Scanner(System.in); statement inside the loop. You should move the statement before the loop.
d. The program compiles, but does not run because there is not prompting message for entering the input.
c To receive input from the keyboard, you need to create an input object from the Scanner class. You should create this object only once in the program. Placing the statement Scanner input = new Scanner(System.in) in the loop causes it to be created multiple times, which is a bad practice and could lead to potential errors. So, the correct answer is C.
You might also like to view...
When you point to a picture in the form section of the split form, the Mini toolbar displays all of the following options EXCEPT:
A) Rotate Picture button. B) Back button. C) Manage Attachments button. D) Forward button.
Which of the following statements is false?
a. Each cell in a GridPane can be empty or can hold one or more JavaFX components, including layout containers that arrange other controls. b. Each component in a GridPane can span multiple columns or rows. c. A TextField (package javafx.scene.control) can accept text input or display text. d. A Slider (package javafx.scene.control) represents a value in the range 0.0–1.0 by default and allows the user to select a number in that range by moving the Slider’s thumb.