How to read user input
Create a Scanner
Import Scanner and connect it to standard input.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
Read a line
nextLine reads text through the Enter key.
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
Read a number safely
Check the available token before reading it so invalid input does not immediately throw an exception.
System.out.print("Age: ");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Next year: " + (age + 1));
} else {
System.out.println("Enter a whole number.");
}
Format output
printf uses placeholders such as %s, %d, and %.2f. %n adds a portable newline.
String item = "Book";
double price = 12.5;
System.out.printf("%s: $%.2f%n", item, price);