AP Computer Science A • Unit 4.6

Using Text Files

Detailed answer explanations for the Unit 4.6 multiple-choice practice questions.

Q1C
Q2D
Q3A
Q4A
Q5B
Q6D
Q7C
Q8B
Q9C
Q10A
Q11B
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

Which object reads tokens and lines from an opened file?

AFile
BIOException
CScanner
DString[]
Correct answer: C. The Scanner is the object that supplies the read methods, so it is what actually pulls tokens and lines out of an opened file.
Explanation

A path name goes into File(String str), and that File object is then passed to Scanner(File f). After that connection is made, every read comes from the scanner: nextInt(), nextDouble(), nextBoolean(), next(), and nextLine() are all its methods.

  • A is not correct: A File receives the path name and is handed to the Scanner constructor, but it has no read methods of its own.
  • B is not correct: IOException is the exception type a file-reading method header declares it may throw when opening the named file fails.
  • D is not correct: A String[] is what split(",") hands back after a line has already been read; it is a result, not a reader.
Q2

Why should file input code consider missing or malformed data?

AhasNext() guarantees that the next item has every type.
BCalling close() repairs an invalid record.
CA File automatically converts every token.
DThe file may not open, or a token may not match the expected type.
Correct answer: D. Both failures the section names are real risks: the named file might not open at all, and a token might not have the type the read method expects.
Explanation

Opening can fail, which is why the method header declares throws IOException. Reading can also fail later, because calling a typed method when the next token does not have that type causes an InputMismatchException. Code that assumes every record is complete and correctly formatted is assuming both of those never happen.

  • A is not correct: hasNext() guarantees only that at least one more item exists; it reports nothing about what type that item has.
  • B is not correct: close() releases the file resource after the final read. It does not inspect or fix the contents of any record.
  • C is not correct: A File only carries the path name to the Scanner; the chosen read method determines how a token is interpreted.
Q3

Which method reads the next complete line from a Scanner?

AnextLine()
Bnext()
CnextBoolean()
DhasNext()
Correct answer: A. nextLine() is the method defined as returning the next complete line as a String.
Explanation

The other reading methods work on tokens, where a token is one item separated by whitespace. nextLine() is the choice when spaces or delimiters belong inside one record, such as a CSV line that is later broken apart with split(",").

  • B is not correct: next() returns only the next token as a String, so it stops at whitespace instead of taking the whole line.
  • C is not correct: nextBoolean() reads a single token and returns a boolean, so it cannot deliver a line of text.
  • D is not correct: hasNext() only tests whether another item is available; it does not consume or return any input.
Q4

Which method can be used to test whether more input is available?

AhasNext()
Bnext()
Cclose()
Dsplit(",")
Correct answer: A. hasNext() is the test that reports whether at least one more item is available to read.
Explanation

Each file-reading loop in the section asks hasNext() first and only then consumes the next item. That ordering is what prevents a read after the input has ended, and it is why the loop can keep processing records until no more remain.

  • B is not correct: next() consumes and returns the next token, so using it as a test would eat the very input you meant to check.
  • C is not correct: close() releases the file resource after the final read, which ends the reading rather than testing it.
  • D is not correct: split(",") breaks apart a line that has already been read and returns a String[]; it says nothing about remaining input.
Q5

What happens if nextBoolean() tries to read the token yes?

AIt returns true.
BIt results in an InputMismatchException.
CIt returns the token as a String.
DIt returns false.
Correct answer: B. The token yes is not a boolean value, and a typed read on the wrong token causes an InputMismatchException.
Explanation

The rule is the same one that stops nextInt() from reading 3.5 or ready: the read method must match the next token's type. The scanner does not translate a word into a Boolean value on your behalf.

  • A is not correct: Nothing in nextBoolean() treats the word yes as a Boolean value, so no true result is produced.
  • C is not correct: Returning the token as a String is what next() does; nextBoolean() is declared to return a boolean.
  • D is not correct: A mismatched token is not quietly converted into a default value, so no false result is produced either.
Q6

Why is a loop useful with file input?

AIt makes every record use the same value.
BIt closes the scanner before the first read.
CIt changes a File into a Scanner.
DIt can process records until hasNext() is false.
Correct answer: D. A loop repeats the read step, so it can keep consuming and processing records until hasNext() reports that no item remains.
Explanation

A file usually holds an unknown number of records, so the program cannot write one read statement per record. The lifecycle in the section is exactly this: test for input, consume and process the next item, repeat, then release the resource when the input ends.

  • A is not correct: Each pass consumes the next item from the file, so successive records receive whatever values the file actually holds.
  • B is not correct: Closing before the first read would release the file resource while input still remains; close() belongs after the final read.
  • C is not correct: The conversion from a path to a reader is done by passing a File to Scanner(File f), which happens once before the loop.
Q7

Which action is generally appropriate after finishing with a file scanner?

ACall next() once more.
BCreate a second scanner for the same completed work.
CClose it when appropriate.
DReplace its File with a String[].
Correct answer: C. Closing the scanner is the step that releases the file resource once the last read is finished.
Explanation

Every file-reading example in the section ends with input.close() after the loop. The checklist states it plainly: close input after the final read.

  • A is not correct: Reading once more after the input has ended is the situation hasNext() exists to prevent, and it does not release the resource.
  • B is not correct: Building a second scanner for work that is already complete adds another connection to the file instead of releasing the one you have.
  • D is not correct: A String[] is a result returned by split, not something a Scanner can be constructed from in place of a File.
Q8

A record stores an int, a double, and a boolean, in that order. What should the program do?

ARead all three fields with nextLine().
BCall the typed read methods in the same order as the fields.
CRead the fields in reverse order to protect earlier values.
DCall close() before reading the Boolean.
Correct answer: B. Fields must be read with the typed methods in the same order they appear in the record, so the calls go nextInt(), then nextDouble(), then nextBoolean().
Explanation

Each call consumes one item, so the next call begins at the following item. Matching the call order to the file order is what puts each value in the right variable, and it is also what keeps each typed method aimed at a token of its own type.

  • A is not correct: nextLine() returns a complete line as a String, so it does not produce the int, double, and boolean values the fields hold.
  • C is not correct: Reading in reverse aims each method at the wrong item, which assigns the wrong field and may cause an InputMismatchException.
  • D is not correct: close() releases the file resource, so calling it early would end the reading before the Boolean field is ever consumed.
Q9

A file contains the following two lines. The following code segment reads the first line. What is printed?

North,18
South,27
String record = input.nextLine();
String[] fields = record.split(",");
System.out.println(fields[0] + "-" + fields[1]);
A18
BNorth,18
CNorth-18
DNothing is printed; an out-of-bounds error occurs.
Correct answer: C. nextLine() takes the whole first line, and split(",") returns the two pieces around the comma, which are then joined with a hyphen between them.
Explanation

For the line shown, fields[0] holds the name piece and fields[1] holds the piece after the comma. The comma itself is the delimiter, so it is not part of either piece; the hyphen in the output comes from the string that the code concatenates between them.

  • A is not correct: Both pieces are concatenated into the printed string, so the name piece in fields[0] appears as well.
  • B is not correct: The comma is the delimiter split divides on, and the printed separator is the hyphen supplied by the concatenation.
  • D is not correct: The line contains one comma, so split produces two pieces and fields[1] is a valid position.
Q10

A file begins with a header line, as shown. The code counts records whose zone matches target. Which change makes the count reflect only the records?

city,zone
Orchard,east
Harbor,west
int count = 0;
while (input.hasNext()) {
    String record = input.nextLine();
    String[] fields = record.split(",");
    if (fields[1].equals(target)) {
        count++;
    }
}
ARead and discard one line before the loop begins.
BCompare fields[0] with target instead.
CRead and discard the first record after the loop ends.
DSplit on " " instead of ",".
Correct answer: A. The first line is a header rather than a record, so it must be read and discarded once before the loop starts processing.
Explanation

The loop as written treats every line the same way, so the header is split and tested along with the real records. The section gives this exact remedy: if the file begins with a header, read and discard that line once before the loop.

  • B is not correct: fields[0] holds the city piece, so comparing it with target would test the wrong field and stop counting by zone entirely.
  • C is not correct: By the time the loop ends, every line including the header has already been split and tested, so discarding one afterward changes no count.
  • D is not correct: These lines are separated by commas, so splitting on a space would not divide them into a name piece and a status piece.
Q11

A file contains the following line. Consider the following code segment. What is the result of running this code segment?

Mina true 4.5
String user = input.next();
boolean active = input.nextBoolean();
double rating = input.nextDouble();
System.out.println(active);
System.out.println(rating);
AIt prints Mina and then true.
BIt prints true and then 4.5.
CIt prints false and then 4.5.
DAn InputMismatchException occurs.
Correct answer: B. The three reads consume the tokens in file order, so active receives the Boolean token and rating receives the decimal token, and those are the two values printed.
Explanation

Each call consumes one item and the next call begins at the following item. Here the call order matches the field order, so next() takes the word, nextBoolean() takes the Boolean token, and nextDouble() takes the decimal token. Only the last two variables are passed to println.

  • A is not correct: The word token is stored in user, and user is never printed, so the name does not appear in the output.
  • C is not correct: nextBoolean() reads the Boolean token actually present in the line, so active does not end up holding the opposite value.
  • D is not correct: Every call matches the type of the token it lands on, so no typed read is applied to a token of the wrong type.