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.

public void setMaximumIntegerDigits(int newValue)<br />

public void setMinimumIntegerDigits(int newValue)<br />

public void setMaximumFractionDigits(int newValue)<br />

public void setMinimumFractionDigits(int newValue)<br />

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

For example, to specify that myFormat should format numbers with at least 10 digits before<br />

the decimal point and at most 3 digits after, you would type:<br />

myFormat.setMinimumIntegerDigits(10);<br />

myFormat.setMaximumFractionDigits(3);<br />

Setting the minimum digits guarantees that those digits will be printed, filled with zeros if<br />

necessary. Setting the maximum digits allows the digits to be printed if they're nonzero or a<br />

place-holding zero (i.e., not the leftmost or rightmost digit). Leftmost and rightmost strings of<br />

zeros will only be printed if it's required to meet the minimum number of digits. If you try to<br />

set a maximum below a minimum or a minimum above a maximum, the last one set takes<br />

precedence. <strong>Java</strong> raises the maximum to meet the minimum or lowers the minimum to meet<br />

the maximum.<br />

Specifying the number of digits is useful when printing many columns of numbers in a tabular<br />

format to the console or in a monospaced font. Example 16.2 prints a three-column table of<br />

the angles between and 360 degrees in degrees, radians and grads without any formatting.<br />

Example 16.2. UglyTable<br />

public class UglyTable {<br />

}<br />

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

}<br />

System.out.println("Degrees \tRadians \tGrads");<br />

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

double radians = Math.PI * degrees / 180.0;<br />

double grads = 400 * degrees / 360;<br />

System.out.println(degrees + "\t" + radians + "\t" + grads);<br />

}<br />

Its output looks like this (not very pretty):<br />

300.0 5.2359877559829835 333.3333333333333<br />

301.0 5.253441048502927 334.44444444444446<br />

302.0 5.27089434102287 335.55555555555554<br />

303.0 5.288347633542813 336.6666666666667<br />

304.0 5.305800926062757 337.77777777777777<br />

305.0 5.3232542185827 338.8888888888889<br />

306.0 5.340707511102643 340.0<br />

Example 16.3 prints the same table with each number formatted to at least three integer digits<br />

and exactly two fraction digits (both minimum and maximum set to 2).<br />

403

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

Saved successfully!

Ooh no, something went wrong!