1.3 Input and Output
Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
println(), print(), and printf()
System.out.println() displays text or variable values on the screen and then adds a newline. System.out.print() does not add a newline. System.out.printf() lets you format values with placeholders.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash
\': single quote
\": double quote
\n: newline
\t: tab
System.out.print("\"Hello\nWorld\"\n");Output:
"Hello
World"Format specifiers
System.out.printf() uses format specifiers (placeholders) to insert values into a string.
%d: integer
%f: floating-point number
%c: character
%s: string
You can also control the format, for example %.2f keeps two decimal places. In Java, %n is the portable newline placeholder for formatted output.
int length = 10;
int width = 5;
double area = length * width;
System.out.printf("Area = %d * %d = %.2f%n", length, width, area);Output:
Area = 10 * 5 = 50.00Controlling the line ending
println() adds a newline automatically. print() and printf() do not unless you include \n or %n yourself.
int num1 = 1, num2 = 2, num3 = 4, num4 = 8;
System.out.print(num1 + ", ");
System.out.print(num2 + ", ");
System.out.print(num3 + ", ");
System.out.println(num4 + "...");Output:
1, 2, 4, 8...Scanner
Scanner can read text from the keyboard and convert it into values. To use it, import java.util.Scanner, create a Scanner, then call methods such as nextInt() and nextDouble().
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Radius: ");
double r = input.nextDouble();
double area = 3.14159 * r * r;
System.out.printf("Area = %.2f%n", area);
}
}One possible run:
Radius: 5
Area = 78.54Here, nextDouble() reads a decimal number and stores it in r.