Small interactive programs and command-line tools need to read input and present results clearly.
For output you already know System.out.println. For aligned or rounded output, use printf-style formatting: System.out.printf("%-10s %6.2f%n", name, price);.
Common format specifiers:
%sany value (callstoString),%dintegers,%ffloating point.%.2ftwo decimals;%8dright-aligned in 8 columns;%-10sleft-aligned.%nthe platform line separator,%%a literal percent sign.
The same patterns work in String.format(...) and "...".formatted(...) when you need the string instead of printing it.
For input, the simplest tool is java.util.Scanner. Wrap System.in once and read tokens or lines: nextLine(), nextInt(), hasNextInt(). A classic gotcha: nextInt() leaves the newline in the buffer, so a following nextLine() returns an empty string. Reading everything with nextLine() and parsing with Integer.parseInt avoids that.
For large inputs (competitive programming, piping big files), Scanner is slow. Use BufferedReader:
var in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) { ... }readLine() returns null at end of input (Ctrl+D on Unix, Ctrl+Z on Windows, or the end of a piped file).
Command-line arguments (args) are another input channel; prefer them for options like file names, and standard input for streams of data.
Example
import java.util.Scanner;
public class Tip {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Bill amount: ");
double bill = Double.parseDouble(in.nextLine().strip());
System.out.print("Tip percent: ");
int pct = Integer.parseInt(in.nextLine().strip());
double tip = bill * pct / 100.0;
System.out.printf("%-6s %8.2f%n", "Bill", bill);
System.out.printf("%-6s %8.2f (%d%%)%n", "Tip", tip, pct);
System.out.printf("%-6s %8.2f%n", "Total", bill + tip);
}
}
// Bill amount: 42.5
// Tip percent: 15
// Bill 42.50
// Tip 6.38 (15%)
// Total 48.88Remember
printf/formattedwith%s %d %.2f %ngive precise output- Reading whole lines and parsing them avoids Scanner's leftover-newline trap
- Use
BufferedReaderfor fast line-by-line input;readLine()returns null at end
Watch out for
- Calling
nextInt()thennextLine()and getting an empty line.