0
0
Javaprogramming~5 mins

Using Scanner class in Java - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aimport java.Scanner.util;
Bimport java.util.Scanner;
Cimport java.lang.Scanner;
Dimport java.io.Scanner;
What does scanner.nextInt() do?
AReads the entire line as a string
BReads the next word as a string
CCloses the scanner
DReads the next integer from input
How can you read a single word (no spaces) from user input?
AUse <code>next()</code>
BUse <code>nextLine()</code>
CUse <code>nextWord()</code>
DUse <code>read()</code>
What is a common problem when mixing nextInt() and nextLine()?
A<code>nextLine()</code> reads leftover newline causing skipped input
BThe program crashes immediately
CInput is converted to uppercase automatically
DScanner closes unexpectedly
Why should you close a Scanner reading from a file?
ATo clear the input buffer
BTo speed up the program
CTo free system resources and avoid file locks
DIt is not necessary to close Scanner
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.