new Scanner(new File(...)) can throw FileNotFoundException, and that exception is checked. A method that contains this line must either catch it or declare throws FileNotFoundException on its own signature, or the compiler refuses the whole file.
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("scores.txt"));
// ...
}
Reading a File Without Knowing Its Length
The same hasNextInt pattern used for unknown-length input on standard input works identically over a file, because both are just Scanner sources.
int total = 0;
while (input.hasNextInt()) {
int value = input.nextInt();
total = total + value;
}
⚠️ Check Before You Consume
Calling nextInt() when nothing is left throws NoSuchElementException. hasNextInt() checks without consuming, which is exactly what guards against that.
The Same Scanner, a Different Source
📌 Nothing About the Reading Logic Changes
Scanner(System.in) and Scanner(new File(...)) are driven by the exact same hasNext/next methods. A loop written to read unknown-length data from the keyboard reads a file the same way, because the source is the only thing that changed.
Practice Questions
MCQ 1
Which statement about opening a file with Scanner is true?
A new Scanner(new File("x.txt")) can throw FileNotFoundException, a checked exception that must be caught or declared
B new Scanner(new File("x.txt")) never fails, since File objects always exist
C FileNotFoundException is an unchecked exception, so handling it is optional
D Scanner cannot be built from a File object, only from System.in
✓ A. A File object can be created for a path that does not exist; the failure surfaces when Scanner tries to open it. That failure is FileNotFoundException, a checked exception, so it must be caught or declared.
MCQ 2
What does hasNextLine() do?
A Reads and returns the next line, consuming it
B Deletes the current line from the file
C Reports whether another line exists, without consuming any input
D Reports whether the file itself exists
✓ C. hasNextLine() only checks; it never consumes a token or a line. nextLine() is the method that actually reads and returns one.
MCQ 3
Why does this code fail to compile?
public static void main(String[] args) {
Scanner input = new Scanner(new File("data.txt"));
}
A Scanner cannot be constructed from a File
B main methods are not allowed to open files
C File objects require their own try block by Java's syntax rules
D FileNotFoundException is a checked exception that main must either catch or declare with throws, and this code does neither
✓ D. The constructor call can throw a checked exception. Since main here neither catches it nor declares throws FileNotFoundException, the compiler refuses the file.
MCQ 4
What happens if nextInt() is called after hasNextInt() has already returned false?
A It returns 0
B It throws NoSuchElementException
C It waits for more input to arrive
D It safely returns the last value read again
✓ B. Once hasNextInt() reports false, there is no more int-shaped data. Calling nextInt() anyway throws NoSuchElementException, exactly what the hasNextInt guard exists to prevent.
MCQ 5
A grader pipes a file's contents in on standard input instead of handing you a real file, since Judge0 has no filesystem. Which statement about the Scanner code you write is true?
A The code must be completely different from code that reads an actual file
B Scanner cannot read from standard input at all
C Scanner(System.in) and Scanner(new File(...)) are driven by the exact same hasNext and next methods, so the same read loop works either way
D Reading from standard input never throws the exceptions file reading can throw
✓ C. The substitution works precisely because both are Scanner sources read through identical methods.
Tier 3 · AP Mastery
Mastery: Using Text Files
MCQ 6
What does this print when data.txt is completely empty (holds nothing at all)?
Scanner input = new Scanner(new File("data.txt"));
int count = 0;
while (input.hasNextInt()) {
input.nextInt();
count++;
}
System.out.println(count);
A 0
B A compile error
C NoSuchElementException is thrown
D Nothing prints; the program hangs waiting for input
✓ A. hasNextInt() is false immediately on an empty file, so the loop body never runs and count stays at its initial value, 0.
MCQ 7
What kind of exception is FileNotFoundException, and what does that mean for code that opens a file?
A Unchecked; handling it is optional
B It does not exist as a real class in java.io
C An Error rather than an Exception, so it can never be caught
D Checked; the compiler forces you to catch it or declare it with throws
✓ D. FileNotFoundException extends IOException, a checked exception, which is exactly why file-opening code needs a catch block or a throws declaration.
MCQ 8
Which of these correctly lets FileNotFoundException propagate out of main rather than catching it?
A public static void main(String[] args) { ... }
B public static void main(String[] args) throws FileNotFoundException { ... }
C public static void main(String[] args) catches FileNotFoundException { ... }
D public static void main(String[] args) throws Exception.printStackTrace() { ... }
✓ B. throws is the keyword that declares a method may propagate a checked exception instead of handling it. catches is not a Java keyword, and D is not valid syntax at all.
MCQ 9
A student guards a loop reading integers with hasNext() instead of hasNextInt(). Why is this riskier on a file that is supposed to hold only integers?
A hasNext() only confirms that a token exists at all, not that it will parse as an int, so a malformed token can still make nextInt() throw InputMismatchException
B hasNext() is always slower than hasNextInt()
C hasNext() cannot be combined with nextInt() at all
D There is no real difference between the two
✓ A. hasNext() checks for the presence of any token, not its shape. A stray non-numeric token passes the hasNext() check and then breaks nextInt().
MCQ 10
A program must total every value in a file without ever being told how many values it holds. Which loop is correct?
A for (int i = 0; i < 100; i++) { total += input.nextInt(); }
B while (true) { total += input.nextInt(); }
C while (input.hasNextInt()) { total += input.nextInt(); }
D int n = input.nextInt(); while (n != -1) { total += n; n = input.nextInt(); }
✓ C. Hardcoding a count assumes a length that may be wrong; looping forever eventually throws once data runs out; assuming a -1 sentinel assumes a value that could legitimately appear in real data. Only the hasNextInt guard is correct for genuinely unknown length.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed.
Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Typically responds within 24 hours
✓
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
34.8% of Tanner’s CSP students score 5s. The national average is 9.6%.
I’m a Student
I’m a Teacher
✓Free AP CSP Big Ideas cheat sheet (PDF)
✓Daily practice questions covering all 5 Big Ideas
✓Create Task tips that actually work — from a real AP teacher
✓Free class codes with student progress tracking
✓3 full practice exams + Top 100 questions for your class
✓Create Task guidance and pseudocode reference sheets
Which AP CS exams are you prepping for?
✓
You’re in!
Your Big Ideas cheat sheet is on its way.
No thanks, I’ll figure it out myself
Avg student improvement: 2+ score levels | Real AP teacher, not just a tutor
AP Cybersecurity — National Launch 2026–27
Get Early Access to AP Cyber
AP Cyber launches nationally fall 2026. Get in early to help shape the course — start free with Unit 1 and the free teacher gradebook.
✓
You’re in — you’re on the AP Cyber early-access list!
Tanner will follow up personally within 48 hours. Your feedback will directly shape what gets built.
Step 1 of 4
Early Access — Limited Spots
Who are you?
Are you a teacher or a student?
I’m a Teacher
I’m a Student
Free to start — Unit 1 and the teacher gradebook are always free, no credit card.
Founding teachers unlock all 5 units and get direct input on what we build.
Not interested right now
Step 2 of 4
Your School
Tell us about your class
Other AP CS courses you teach
Your Situation
Tell us about yourself
Step 3 of 4
Classroom Needs
What does your classroom need? (select all that apply)
How You Study
What would help you most? (select all that apply)
Step 4 of 4
Almost Done
Where should we send your early-access details?
Free gradebook + Unit 1 | Your feedback shapes the course | Built by a real AP teacher