Java Reference
In-Depth Information
that we don't see all of them. One way to truncate is to cast a double to an int , which
truncates all of the digits after the decimal point. We could do that, but we probably
want at least some of those digits. Say, for example, that we want to report two digits
after the decimal point. The trick is to bring the two digits we want to the other side of
the decimal point. We can do that by multiplying by 100 and then casting to int :
(int) (n * 100.0)
This expression gets us the digits we want, but now the decimal point is in the wrong
place. For example, if n is initially 3.488834 , the preceding expression will give us
348 . We have to divide this result by 100 to turn it back into the number 3.48:
(int) (n * 100.0) / 100.0
While we're at it, we can make one final improvement. Notice that the original num-
ber was 3.488834 . If we do simple truncation we get 3.48 , but really this number is
closer to 3.49 . We can round to the nearest digit by calling the Math.round method on
the number instead of casting it:
Math.round(n * 100.0) / 100.0
This is an operation that we are likely to want to perform on more than one number,
so it deserves to be included in a method:
public static double round2(double n) {
return Math.round(n * 100.0) / 100.0;
}
Getting back to our pseudocode for the table, we can incorporate calls on the
round2 method to get a bit closer to actual Java code:
set all of x, y, and t to 0.
for (given number of steps) {
add timeIncrement to t.
add xIncrement to x.
reset y to yVelocity * t + 0.5 * ACCELERATION * t * t.
report step #, round2(x), round2(y), round2(t).
}
It would be nice if the values in the table were aligned. To get numbers that line up
nicely, we would have to use formatted output, which we will discuss in Chapter 4.
For now, we can at least get the numbers to line up in columns by separating them
with tab characters. Remember that the escape sequence \t represents a single tab.
If we're going to have a table with columns, it also makes sense to have a header
for the table. And we probably want to include a line in the table showing the initial
 
Search WWH ::




Custom Search