Programming and Problem Solving with Java

(やまだぃちぅ) #1
691

more digits, fewer stars are needed, and if it has fewer digits then more stars must be con-
catenated. The number of stars to add is


12 – dollar.format(value).length


because the dollar sign takes up one of the thirteen character positions. The maximum value
of this expression is 8, because the format requires at least three decimal digits and a deci-
mal point. Thus, if we use a string constant called STARSthat contains eight stars, we can write


STARS.substring( 0 , 12 – dollar.format(value).length)


to get a string with the proper number of stars. All we have left to do is to concatenate the
pieces to form the desired string.


"$"+ STARS.substring( 0 , 12 – dollar.format(value).length) + dollar.format(value)


Look closely at this expression to be certain that you understand how it works. Many pro-
gramming problems require that output values be precisely formatted. In such cases, you may
need to use complex combinations of the string operations that Java provides. Breaking an
output format into its component pieces and deciding how to format each piece before con-
catenating them together is a common strategy for dealing with this complexity.

Free download pdf