23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Java</strong> I/O<br />

align the decimal points in a column of numbers. You create a FieldPosition object by<br />

passing one of these numeric constants into the FieldPosition() constructor:<br />

public FieldPosition(int field)<br />

For example, to get the integer field:<br />

FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);<br />

There's a getField() method that returns this constant:<br />

public int getField()<br />

Next you pass this object into one of the format() methods that takes a FieldPosition<br />

object as an argument:<br />

NumberFormat nf = NumberFormat().getNumberInstance();<br />

StringBuffer sb = nf.format(2.71828, new StringBuffer(), fp);<br />

When format() returns, the FieldPosition object contains the beginning and ending index<br />

of the field in the string. These methods return those items:<br />

public int getBeginIndex()<br />

public int getEndIndex()<br />

You can subtract getBeginIndex() from getEndIndex() to find the number of characters in<br />

the field. If you're working with a monospaced font, this may be all you need to know. If<br />

you're working with a proportionally spaced font, you'll probably use<br />

java.awt.FontMetrics to measure the exact width of the field instead. Example 16.6 shows<br />

how to work in a monospaced font. This is essentially another version of the angle table. Now<br />

a FieldPosition object is used to figure out how many spaces to add to the front of the<br />

string; the getSpaces() method is simply used to build a string with a certain number of<br />

spaces.<br />

Example 16.6. PrettierTable<br />

import java.text.*;<br />

public class PrettierTable {<br />

public static void main(String[] args) {<br />

NumberFormat myFormat = NumberFormat.getNumberInstance();<br />

FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);<br />

myFormat.setMaximumIntegerDigits(3);<br />

myFormat.setMaximumFractionDigits(2);<br />

myFormat.setMinimumFractionDigits(2);<br />

System.out.println("Degrees Radians Grads");<br />

for (double degrees = 0.0; degrees < 360.0; degrees++) {<br />

String radianString = myFormat.format(<br />

radianString = getSpaces(3 - fp.getEndIndex()) + radianString;<br />

String gradString = myFormat.format(<br />

gradString = getSpaces(3 - fp.getEndIndex()) + gradString;<br />

409

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!