Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
System.out.println()
System.out.println() displays text or values and then ends the line.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash\': single quote\": double quote\n: newline\t: tab
System.out.println("\"Hello\nWorld\"");Output:
"Hello
World"KNOWLEDGE QUIZ
Formatted output
You can also insert values into a string with placeholders.
%d: integer%f: floating-point number%s: string
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.00The placeholders correspond to the following arguments in order; %.2f formats a floating-point value with two decimal places.
System.out.printf("Area = %d * %d = %.2f%n", length, width, area);KNOWLEDGE QUIZ
Controlling the line ending
System.out.println() ends with a newline, while System.out.print() leaves the cursor on the same line.
int num1 = 1;
int num2 = 2;
int num3 = 4;
int num4 = 8;
System.out.print(num1 + ", ");
System.out.print(num2 + ", ");
System.out.print(num3 + ", ");
System.out.print(num4 + "...");Output:
1, 2, 4, 8...Scanner input
Scanner reads keyboard input. Create one for System.in, then call next(), nextInt(), or nextDouble().
next() returns a String; nextInt() and nextDouble() parse numeric input directly.
Scanner scanner = new Scanner(System.in);
System.out.print("Radius: ");
double r = scanner.nextDouble();
double area = Math.PI * r * r;
System.out.printf("Area = %.2f%n", area);One possible run:
Radius: 5
Area = 78.54Here, scanner.nextDouble() reads a double directly, while Math.PI is Java’s standard-library constant for pi.
KNOWLEDGE QUIZ
Output Lab Bench
Run the three code cards in order and watch how each statement changes the terminal.
Calculate the distance between two points
Read two coordinate points and print the planar distance.
- Read x1, y1, x2, and y2 as four floating-point numbers.
- Apply the distance formula to compute the result.
- Print the distance rounded to two decimal places.
Build a temperature record card
Read one Celsius value, store it in clearly named variables, convert it to Fahrenheit, and print a compact report.
- Read one Celsius value with Scanner.
- Store the Fahrenheit result in a variable named fahrenheit.
- Create a string variable named reportTitle and print it together with the converted value.