3.7. Input and Output
To make our example programs more interesting, we want to accept input and properly format the program output. Of course, modern programs use a GUI for collecting user input. However, programming such an interface requires more tools and techniques than we have at our disposal at this time. Our first order of business is to become more familiar with the Java programming language, so we use the humble console for input and output.
3.7.1. Reading Input
You saw that it is easy to print output to the console window just by calling IO.println. Reading from the console is just as simple.
The readln method reads one line of input and returns it as a string value. You can optionally pass a prompt string as an argument.
String name = IO.readln("What is your name? ");
To read an integer, use the Integer.parseInt method to convert the entered string into an integer.
int age = Integer.parseInt(IO.readln("How old are you? "));
Similarly, the parseDouble method converts a string to a floating-point number.
double rate = Double.parseDouble(IO.readln("Interest rate: "));
The program in Listing 3.2 asks for the user’s name and age and then prints a message like
Hello, Cay. Next year, you'll be 65.
Listing 3.2 InputDemo.java
/**
* This program demonstrates console input.
*/
void main() {
// get first input
String name = IO.readln("What is your name? ");
// get second input
int age = Integer.parseInt(IO.readln("How old are you? "));
// display output on console
IO.println("Hello, " + name + ". Next year, you'll be " + (age + 1) + ".");
}
3.7.2. Formatting Output
You can print a number x to the console with the statement IO.print(x). That command will print x with the maximum number of nonzero digits for that type. For example,
double x = 10000.0 / 3.0; IO.print(x);
prints
3333.3333333333335
That is a problem if you want to display, for example, dollars and cents.
The remedy is the formatted method, which follows the venerable conventions from the C library. For example, the call
IO.print("%8.2f".formatted(x));
prints x with a field width of 8 characters and a precision of 2 characters. That is, the printout contains a leading space and the seven characters
3333.33
You can supply multiple arguments to formatted. For example:
IO.print("Hello, %s. Next year, you'll be %d.".formatted(name, age + 1));
Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. Table 3.5 shows all conversion characters.
The uppercase variants produce uppercase letters. For example, "%8.2E" formats 3333.33 as 3.33E+03, with an uppercase E.
Table 3.5: Conversions for formatted
Conversion Character |
Type |
Example |
d |
Decimal integer |
159 |
x or X |
Hexadecimal integer. For more control over hexadecimal formatting, use the HexFormat class. |
9f |
o |
Octal integer |
237 |
f or F |
Fixed-point floating-point |
15.9 |
e or E |
Exponential floating-point |
1.59e+01 |
g or G |
General floating-point (the shorter of e and f) |
— |
a or A |
Hexadecimal floating-point |
0x1.fccdp3 |
s or S |
String |
Hello |
c or C |
Character |
H |
b or B |
boolean |
true |
h or H |
Hash code |
42628b2 |
tx or Tx |
Legacy date and time formatting. Use the java.time classes instead—see Chapter 6 of Volume II. |
— |
% |
The percent symbol |
% |
n |
The platform-dependent line separator |
— |
In addition, you can specify flags that control the appearance of the formatted output. Table 3.6 shows all flags. For example, the comma flag adds group separators. That is,
IO.println("%,.2f".formatted(10000.0 / 3.0));
prints
3,333.33
You can use multiple flags, for example "%,(.2f" to use group separators and enclose negative numbers in parentheses.
Table 3.6: Flags for printf
Flag |
Purpose |
Example |
+ |
Prints sign for positive and negative numbers. |
+3333.33 |
space |
Adds a space before positive numbers. |
| 3333.33| |
0 |
Adds leading zeroes. |
003333.33 |
- |
Left-justifies field. |
|3333.33 | |
( |
Encloses negative numbers in parentheses. |
(3333.33) |
, |
Adds group separators. |
3,333.33 |
# (for f format) |
Always includes a decimal point. |
3,333. |
# (for x or o format) |
Adds 0x or 0 prefix. |
0xcafe |
$ |
Specifies the index of the argument to be formatted. For example, %1$d %1$x prints the first argument in decimal and hexadecimal. |
159 9F |
< |
Formats the same value as the previous specification. For example, %d %<x prints the same number in decimal and hexadecimal. |
159 9F |
Figure 3.6 shows a syntax diagram for format specifiers.
Figure 3.6: Format specifier syntax
