Java Reference
In-Depth Information
}
}
} catch
catch ( IOException e ) {
throw
throw new
new RuntimeException ( "IOException: " + e );
}
return
return sum ;
}
Aligning Strings
Problem
You want to align strings to the left, right, or center.
Solution
Do the math yourself, and use substring (see Taking Strings Apart with Substrings ) and a
StringBuilder (see Putting Strings Together with StringBuilder ) . Or, use my StringAlign
class, which is based on the java.text.Format class. For left or right alignment, use
String.format() .
Discussion
Centering and aligning text comes up fairly often. Suppose you want to print a simple report
with centered page numbers. There doesn't seem to be anything in the standard API that will
do the job fully for you. But I have written a class called StringAlign that will. Here's how
you might use it:
public
public class
class StringAlignSimple
StringAlignSimple {
public
public static
void main ( String [] args ) {
// Construct a "formatter" to center strings.
StringAlign formatter = new
static void
new StringAlign ( 70 , StringAlign . Justify . CENTER );
// Try it out, for page "i"
System . out . println ( formatter . format ( "- i -" ));
// Try it out, for page 4. Since this formatter is
// optimized for Strings, not specifically for page numbers,
// we have to convert the number to a String
System . out . println ( formatter . format ( Integer . toString ( 4 )));
Search WWH ::




Custom Search