Java Reference
In-Depth Information
A second way, as shown in example 5 on the previous page, combines
Strings and variables in the same line using concatenation. Using a plus sign (+),
Java allows a concatenation , or joining, of these types of data in a single output
line of code. In both example 4 and 5, leaving a space after the word, is, keeps the
message and the answer from running together.
Additionally, programmers may invoke methods in their output, as shown in
example 6. The Math.round() method rounds the answer to the nearest integer;
the println() method then prints the answer.
The output code for the Body Mass Index Calculator program is shown in
Figure 3-19. Line 39 begins with an escape character tab, followed by text. Then
the index value from the previous calculation is rounded to an integer with
the Math.round() method and concatenated to the text, YOUR BODY MASS
INDEX IS. Finally, a period is concatenated to complete the output sentence.
Lines 38 and 40 print blank lines before and after the output message. Lines 41
and 42 are the closing braces for the main() method and class blocks, respectively.
37
// output
38
System .out.println () ;
39
System .out.println ( "\tYOUR BODY MASS INDEX IS " + Math .round ( index ) + "." ) ;
40
System .out.println () ;
41
}
42 }
FIGURE 3-19
The following step enters the code that uses variables, concatenation, and the
Math.round() method to produce output on the display.
To Enter Code to Display Output
1. With the insertion point on line 37 in the coding window, type the code
from Figure 3-19.
The output code is displayed in the coding window (Figure 3-20). The
calculated BMI will display as a rounded integer value in the same line as
the output message. Depending on your TextPad settings, the closing brace
in line 42 may display in a different column.
Search WWH ::




Custom Search