Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

the following program segment is being used to read a college name, the…

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()

Explanation:

🆕 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":

  1. The name of the College is stored on one line.
  2. 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 is input.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 is input.nextInt().
  • tuition: The code already uses input.nextInt() to read the tuition value right after numStu.

Therefore:

  • / missing code 1 / must be input.nextLine()
  • / missing code 2 / must be input.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.

Answer:

input.nextLine() input.nextInt()