Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

8.5: Text Files and Scanner

A Scanner reads sequential input. Establish what tokens or lines the input contains before choosing a reading method, and close the scanner after use.

College Board Unit 4

How it works

Reading data from a text file is new to the 2026 AP CSA framework. A Scanner constructed over a File reads its input in order, and hasNext reports whether anything remains to read. The standard shape is a while loop that tests before every read: while (input.hasNext()), then a read method that matches the data, such as next, nextLine, nextInt, or nextDouble. Tokens are separated by whitespace, and runs of whitespace collapse into one separator, so leading spaces and blank runs never produce empty tokens.

Check whether more input remains before reading, and match the read method to the data type.

Common error

Mixing token and line reads, which leaves a partial line behind and misaligns everything after it.

Worked example

Java

Scanner input = new Scanner("12 7 4");
int total = 0;
while (input.hasNext()) total += input.nextInt();
input.close();
System.out.println(total);

Output

23

The input contract guarantees integer tokens, so each nextInt safely consumes the next value. The in-memory source keeps the example reproducible.

Exercises

8.5.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

Scanner input = new Scanner("Ada 17");
String name = input.next();
int age = input.nextInt();
System.out.println(name + ":" + (age + 1));
input.close();
Show solution

Output

Ada:18

The first token is text, and the second is parsed as an integer before addition.

8.5.2 · Write code

Write public static int sumTokens(Scanner input). Assume every remaining token is an integer. Consume them all and return the sum. The caller owns and closes the scanner. For a text file, the same method can receive a Scanner connected to that file.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int sumTokens(Scanner input) {
    int sum = 0;
    while (input.hasNext()) sum += input.nextInt();
    return sum;
}

Check your code

Java

Scanner a = new Scanner("5 -2 8"); System.out.println(sumTokens(a)); a.close();
Scanner b = new Scanner(""); System.out.println(sumTokens(b)); b.close();

Expected output

11
0
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic