Objectives
- Perform basic output in Java
- Perform basic input in Java
Output strings may often need to contain special characters that are not possible to type into the source code. The language has escape sequences to represent some of those characters. The escape sequences available in Java are listed in the table below. The demonstration program TestEscape.java demonstrates the use of escape sequences.
character | escape seq |
---|---|
newline | \n |
carriage return (no newline) | \r |
tab | \t |
backspace | \b |
backslash | \\ |
single quote | \' |
double quote | \" |
In-class spinner to demonstrate '\r' usage: TestSpin.java
Display a greeting on the screen: System.out.println("Hello, world!"); Display the same greeting, but use two statements to do it: System.out.print("Hello"); System.out.println(", world!"); Display a variable's value: double rate = 15.75; System.out.println(rate); Display a string and a variable's value: System.out.println("The rate is " + rate); Display a string and a variable's value formatted to two decimal positions: System.out.printf("The rate is %.2f\n", rate); Display a string and a variable's value formatted to seven columns with two decimal positions: System.out.printf("The rate is %7.2f\n", rate);
Please note that it is good form to prompt the user for input. Prompting means displaying text before asking for input when using a text environment. Generally, you will want to use print instead of println for prompts so the user's cursor will stay on the same line as the prompt.
Set up a new Scanner object: import java.util.Scanner; // at very beginning of source code Scanner kbd = new Scanner(System.in); Get a string from the user: String name; System.out.print("Enter your name: "); name = kbd.nextLine(); Get an integer from the user: int age; System.out.print("Enter your age: "); age = kbd.nextInt(); Get a double precision floating-point number from the user: double rate; System.out.print("Enter your hourly wage: "); rate = kbd.nextDouble();