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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

This whole class is just a wrapper around an int position, which is set by the constructor and<br />

the setIndex() mutator method. It's returned by the getIndex() method. As a<br />

NumberFormat parses a string, it updates the associated ParsePosition's index. Thus, when<br />

passed into a parse() method, the ParsePosition contains the index where parsing will<br />

begin. When the parse() method returns, the ParsePosition contains the index<br />

immediately after the last character parsed. If parsing fails, the parse position is unchanged.<br />

Some number formats can only read integers, not floating point numbers. The<br />

isParseIntegerOnly() method returns true if this is the case, false otherwise.<br />

public boolean isParseIntegerOnly()<br />

public void setParseIntegerOnly(boolean value)<br />

The setParseInteger() method lets you specify that the format should only parse integers.<br />

If a decimal point is encountered, then parsing should stop.<br />

Example 16.8 is a simple program of the sort that's common in CS 101 courses. The<br />

assignment is to write a program that reads a number entered from the command line and<br />

prints its square root. Successive numbers are read until a negative number is entered, at<br />

which point the program halts. Although this is a very basic exercise, it's relatively complex<br />

in <strong>Java</strong>, because <strong>Java</strong> separates string parsing from basic I/O. Nonetheless, while it may not<br />

be suitable for the first week's homework, students should be able to handle it by the end of<br />

the semester.<br />

Example 16.8. RootFinder<br />

import java.text.*;<br />

import java.io.*;<br />

public class RootFinder {<br />

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

Number input = null;<br />

try {<br />

BufferedReader br = new BufferedReader(new<br />

InputStreamReader(System.in));<br />

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

while (true) {<br />

System.out.println("Enter a number (-1 to quit): ");<br />

String s = br.readLine();<br />

try {<br />

input = nf.parse(s);<br />

}<br />

catch (ParseException e) {<br />

System.out.println(s + " is not a number I understand.");<br />

continue;<br />

}<br />

double d = input.doubleValue();<br />

if (d < 0) break;<br />

double root = Math.sqrt(d);<br />

System.out.println("The square root of " + s + " is " + root);<br />

}<br />

}<br />

413

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

Saved successfully!

Ooh no, something went wrong!