QUESTION IMAGE
Question
the following program segment is being used to read a college name, the number of students, and the tuition from the file called \colleges.txt\. the name of the college is stored on one line and the number of students and tuition are stored on the following line.
select the correct option to replace the missing code.
java
try {
scanner input = new scanner(new file(\colleges.txt\));
while (input.hasnext()) {
string name = / missing code 1 /;
int numstu = / missing code 2 /;
int tuition = input.nextint();
input.nextline();
if (10000 < numstu && numstu < 20000) {
system.out.println(name + \ \ + numstu + \ \ + tuition);
}
}
} catch(ioexception e) {
system.out.println();
}
which is the correct option to replace the missing code?
- input.nextline() input.nextint()
- input.nextint() input.next()
- input.next() input.next()
🆕 New Concept Discovered: Java Scanner Tokenization and Line Parsing
Reading mixed text and numeric data from files.
Step 1: Analyze the File Structure
The problem states how the data is structured in the file "colleges.txt":
- The name of the College is stored on one line.
- The number of students and the tuition are stored on the following line.
This means each college entry spans two lines:
- Line 1:
[College Name](which can contain spaces, so we must read the entire line). - Line 2:
[number of students] [tuition](two integers separated by whitespace).
Step 2: Match Variables to Scanner Methods
Let's look at the code inside the loop:
String name = /* missing code 1 */;
int numStu = /* missing code 2 */;
int tuition = input.nextInt();
input.nextLine(); // Consumes the rest of the line/newline character
name: Since the college name is on its own line and may contain spaces (e.g., "State University"), we need to read the entire line. The appropriate method isinput.nextLine().numStu: The number of students is an integer located on the next line, preceding the tuition integer. The appropriate method to read this integer isinput.nextInt().tuition: The code already usesinput.nextInt()to read the tuition value right afternumStu.
Therefore:
/ missing code 1 /must beinput.nextLine()/ missing code 2 /must beinput.nextInt()
Step 3: Select the Correct Option
We look for the option that provides these two methods in order:
- Option 1:
input.nextLine() input.nextInt()
This matches our analysis perfectly.
Snap & solve any problem in the app
Get step-by-step solutions on Sovi AI
Photo-based solutions with guided steps
Explore more problems and detailed explanations
input.nextLine() input.nextInt()