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.

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

Here's a sample run:<br />

% java RootFinder<br />

Enter a number (-1 to quit):<br />

87<br />

The square root of 87 is 9.327379053088816<br />

Enter a number (-1 to quit):<br />

3.151592<br />

The square root of 3.151592 is 1.7752723734683644<br />

Enter a number (-1 to quit):<br />

2,345,678<br />

The square root of 2,345,678 is 1531.5606419596973<br />

Enter a number (-1 to quit):<br />

2.998E+8<br />

The square root of 2.998E+8 is 1.7314733610425546<br />

Enter a number (-1 to quit):<br />

299800000<br />

The square root of 299800000 is 17314.733610425545<br />

Enter a number (-1 to quit):<br />

0.0<br />

The square root of 0.0 is 0.0<br />

Enter a number (-1 to quit):<br />

four<br />

four is not a number I understand.<br />

Enter a number (-1 to quit):<br />

4<br />

The square root of 4 is 2.0<br />

Enter a number (-1 to quit):<br />

(12)<br />

(12) is not a number I understand.<br />

Enter a number (-1 to quit):<br />

-1<br />

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

These results tell you a few things about the default number format on the platform where I<br />

ran it (U.S. English Solaris, JDK 1.1.4). First, it doesn't understand exponential notation. The<br />

square root of 2.998E+8 is not 1.7314733610425546; it's 1.7314733610425546E+4. The<br />

number format parsed up to the first character it didn't recognize (E) and stopped, thus<br />

returning the square root of 2.998 instead. You can also see that this number format doesn't<br />

understand negative numbers represented by parentheses or words like "four." On the other<br />

hand, it can parse numbers with thousands separators like 2,345,678. This is more than the I/O<br />

libraries in most other languages can do. With the appropriate, nondefault number format,<br />

<strong>Java</strong> could parse (12), four, and 2.998E+8 as well.<br />

16.6 Decimal Formats<br />

The java.text package contains a single concrete subclass of NumberFormat,<br />

DecimalFormat. The DecimalFormat class provides even more control over how floating<br />

point numbers are formatted:<br />

public class DecimalFormat extends NumberFormat<br />

414

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

Saved successfully!

Ooh no, something went wrong!