Section 1.11 Input and Output
We often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Java does have a way to create dialog boxes, there is a
Scanner
class we can use to get input from the command line.
Listing 1.11.1 asks the user for their age in years and prints the approximate age in days:
Any
import
statements that your program does should come at the beginning of the file. In line 6, the left-hand side of the assignment declares a Scanner
object named input
. The right-hand side constructs a new
Scanner
object based on the user’s keyboard (System.in
). The System
class is automatically imported for you.Line 8 prints the prompt for the user. Notice that it uses
System.out.print()
instead of System.out.println()
; the output will not be followed by a newline; we want the input cursor on the same line as the prompt.Line 9 gets the next integer from the
Scanner
and assigns it to years
.Lines 12 and 13 produce the output, using the
+
operator to concatenate strings; days
will implicitly be converted to a string in the process.Here is what the output of running this program looks like:
Enter your age in years: 27 Your age in days is approximately 9855.
The
Scanner
class reads tokens from the input; it skips over any leading white space (blanks, tabs, and newlines), and reads up to, but not including, the next blank, tab, or newline.) Here are other Scanner
methods:Scanner
MethodsnextInt() |
Reads next token, converts it to an integer, and returns it. |
nextDouble() |
Reads next token, converts it to a double, and returns it. |
nextBoolean() |
Reads next token, converts it to a boolean, and returns it. |
next() |
Reads next token and returns it as a String. |
nextLine() |
Advances scanner past the current line and returns the skipped String. (This has the same effect as reading the next line up to and including a newline, and returning the line without the newline character.) |
Subsection 1.11.1 String Formatting
While we can use
System.out.println()
for output, it often gives us output that is less than pleasing, as in Listing 1.11.3.Here is its output:
Enter price: $12.95 Your new price is $12.011125.
It is often useful to have more control over the look of your output. Fortunately, Java provides us with an alternative called formatted printing. The
System.out.format()
method as its first argument a format string— a template in which words or spaces that will remain constant are combined with placeholders for variables that will be inserted into the string. Let’s expand on our “age in days” program to ask the user’s name:Let’s examine lines 15 and 16. The first argument to
format()
is the format string. The %d
and %s
are format specifiers; you can think of them as placeholders for values. The %d
specifier says that the placeholder will be filled in by a decimal integer value; %s
is a placeholder for a String value.The third specifier
%n
is special. It is not a placeholder for a value; instead, it stands for newline, as format()
does not automatically print a newline character at the end of its output. You can also use the escape sequence \n
, but %n
is preferred.The remaining arguments to
format()
are the values that will fill in the %d
and %s
placeholders. The values are taken in order from left to right and inserted into the format string. Here’s what the output looks like:The format string may contain one or more conversion specifications. A conversion character tells the format operator what type of value is going to be inserted into that position in the string. In the example above, the
s
specifies a string, while the d
specifies an integer. Other possible type specifications include f
, e
, g
, c
, or %
. Table 1.11.5 summarizes all of the various type specifications.Character | Output Format |
---|---|
d |
Integer |
u |
Unsigned integer |
f |
Floating point (default six decimal places if needed) |
e |
Floating point as exponential notation: m.dddddde+/-xx |
E |
Floating point as exponential notation: m.ddddddE+/-xx |
g |
Use %e for exponents less than \(-4\) or greater than \(+5\text{,}\) otherwise use %f
|
c |
Single character |
s |
String |
% |
Insert a literal % character |
n |
Insert a newline character |
In addition to the format character, you can also include a format modifier between the
%
and the format character. Format modifiers can be used to specify the field width along with a number of digits after the decimal point. Table 1.11.6 explains these format modifiers.Modifier | Example | Description |
---|---|---|
number | %20d |
Put the value in a field width of 20 |
- |
%-20d |
Put the value in a field 20 characters wide, left-justified |
+ |
%20d |
Put the value in a field 20 characters wide, right-justified |
0 |
%020d |
Put the value in a field 20 characters wide, fill in with leading zeros |
. |
%20.2f |
Put the value in a field 20 characters wide with 2 characters to the right of the decimal point |
Listing 1.11.7 gives some examples of
System.out.format()
.The width given in the example is the minimum space allocated for the output. If output requires more space, as in the last line, it will use more.
Here is the output:
|Java| | Java| |Java | |123456| | 123456| |123456 | | 123,456| |12345.678901| | 12345.679| |12,345.679| | 1.235e+04| |12345.6789012|
This program also gives examples of how to write a comment in Java. The characters
//
introduce a single-line comment; Java ignores everything from the //
to the end of line (lines 14, 15, and 17). Multi-line coments begin with /*
and end with */
(lines 8-11).You have attempted of activities on this page.