Output and Input: Talking to the Console
In Java, showing information to the user and taking input are the two sides of the same coin. Here is a guide on how to handle both using print, printf, and Scanner.
To build interactive software, your program needs to display data clearly and listen to what the user says. In Java, we use Print methods for output and the Scanner class for input.
1. Output: print vs. printf
Java provides different ways to send text to the terminal.
The Basic Options: print and println
print(): Displays text and stays on the same line.println(): Displays text and moves the cursor to a new line.
System.out.print("This is ");
System.out.print("all one line.");
System.out.println("\nThis starts on a new line.");
The Professional Option: printf
printf stands for "print formatted." It allows you to build complex strings with "placeholders" for your variables. This is much cleaner than using many + signs.
Common Placeholders:
%s: String%d: Integer (Whole number)%f: Float/Double (Decimal)%n: Newline
String name = "YourName";
int level = 5;
double score = 95.5;
// Using printf for a clean summary
System.out.printf("User: %s | Level: %d | Score: %.1f%% %n", name, level, score);
Tip:
%.1ftells Java to show only 1 decimal place.
2. Input: Capturing User Data
To read what the user types, we use the Scanner class.
Step-by-Step Implementation:
- Import: Add
import java.util.Scanner;at the very top of your file. - Initialize: Create the scanner object inside your main method.
- Read: Use the method that matches your data type.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your username: ");
String user = input.nextLine(); // Reads a String
System.out.print("Enter your age: ");
int age = input.nextInt(); // Reads an Integer
System.out.printf("Hello %s, you are %d years old!%n", user, age);
input.close();
}
}
3. Quick Reference Table
| Feature | Method | Purpose |
|---|---|---|
| Simple Output | System.out.println() |
Print text and jump to the next line. |
| Formatted Output | System.out.printf() |
Print variables inside a template. |
| Text Input | input.nextLine() |
Read a full sentence from the user. |
| Number Input | input.nextInt() |
Read a whole number from the user. |
💡 Challenge: The Formatter
Write a program that asks the user for their favorite book, its price, and the year it was published. Use printf to display the result in this exact format:
Book: [Name] | Price: $[Price] | Year: [Year]
```