Summary - Input and output
- Java course
- Beginner
- Lesson 99/116
- 5 min
Combine Scanner, printf and BufferedReader to write an interactive menu.
Summary - Input and output
In this group you learned to read input with Scanner, produce formatted output with printf and read efficiently with BufferedReader. try-with-resources gave you a safe way to close resources.
Now you will combine everything to write a small interactive menu: read a number from the user and produce output based on the menu choice. This summary lesson has 5 steps and includes one code task.
Practice Interactive menu
Read a number from the user with nextInt (1 or 2). Use switch to produce output based on the choice: for 1 print Seçim: 1%n with printf, for 2 print Seçim: 2%n. The user will type 1. Print the cue Seç: .
Starter code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner, read a number, use switch to produce menu output
}
}Sample solution
Scanner input = new Scanner(System.in);
System.out.print("Seç: ");
int choice = input.nextInt();
switch (choice) {
case 1: System.out.printf("Seçim: 1%n"); break;
case 2: System.out.printf("Seçim: 2%n"); break;
}Expected output
Seç: Seçim: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool is most efficient for multi-line input?
- Scanner
- printf
- System.out
- BufferedReader Correct answer
Explanation: BufferedReader buffers lines, so it is faster for multi-line input.
2 Match each tool to its job
| Term | Meaning |
|---|---|
Scanner |
Easy input |
printf |
Formatted output |
BufferedReader |
Fast reading |
try-with-resources |
Auto closing |
3 Close the resource safely
try (Scanner input = new Scanner(System.____)) {
String line = input.nextLine();
}
try (Scanner input = new Scanner(System.in)) {
String line = input.nextLine();
}
Explanation: System.in is used safely inside try-with-resources.