Recall & Review
beginner
What is the purpose of the Scanner class in Java?The Scanner class is used to read input from various sources like keyboard input, files, or strings. It helps to get user input easily.Click to reveal answer
beginner
How do you create a Scanner object to read input from the keyboard?
You create it by writing:
Scanner scanner = new Scanner(System.in); This connects the Scanner to the keyboard input.Click to reveal answer
beginner
Which method of Scanner reads a whole line of text including spaces?
The method
nextLine() reads the entire line of input including spaces until the user presses Enter.Click to reveal answer
intermediate
What happens if you use
nextInt() and then nextLine() without extra handling?After
nextInt(), the newline character remains in the input buffer. So nextLine() reads that leftover newline, often causing unexpected behavior.Click to reveal answer
intermediate
How do you properly close a Scanner object and why is it important?
You close it by calling
scanner.close();. Closing frees system resources and avoids resource leaks, especially when reading from files.Click to reveal answer
Which import statement is needed to use the Scanner class?
✗ Incorrect
The Scanner class is in the java.util package, so you import it with
import java.util.Scanner;.What does
scanner.nextInt() do?✗ Incorrect
nextInt() reads the next integer value from the input.How can you read a single word (no spaces) from user input?
✗ Incorrect
next() reads the next token (word) separated by whitespace.What is a common problem when mixing
nextInt() and nextLine()?✗ Incorrect
After
nextInt(), the newline character remains and nextLine() reads it, skipping user input.Why should you close a Scanner reading from a file?
✗ Incorrect
Closing Scanner frees resources and releases file locks, preventing resource leaks.
Explain how to use the Scanner class to read an integer and a full line of text from the keyboard.
Remember the leftover newline after reading numbers.
You got /4 concepts.
Describe why and how to close a Scanner object in Java.
Think about what happens if you leave files open.
You got /4 concepts.