CS 101 Homework

import java.text.*;
import java.io.*;


public class RootFinder {

  public static void main(String[] args) {
  
    Number input = null;
    
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      NumberFormat nf = NumberFormat.getInstance();
      while (true) {
        System.out.println("Enter a number (-1 to quit): ");
        String s = br.readLine();
        try {
          input = nf.parse(s);
        }
        catch (ParseException e) {
          System.out.println(s + " is not a number I understand.");
          continue;
        }
        double d = input.doubleValue();
        if (d < 0) break;
        double root = Math.sqrt(d);
        System.out.println("The square root of " + s + " is " + root);
      }
    }
    catch (IOException e) {
      System.err.println(e);  
    }
    
  }

}


Output:
% java RootFinder
Enter a number (-1 to quit): 
87
The square root of 87 is 9.327379053088816
Enter a number (-1 to quit): 
65.4
The square root of 65.4 is 8.087026647662292
Enter a number (-1 to quit): 
3.151592
The square root of 3.151592 is 1.7752723734683644
Enter a number (-1 to quit): 
2,345,678
The square root of 2,345,678 is 1531.5606419596973
Enter a number (-1 to quit): 
2.998E+8
The square root of 2.998E+8 is 1.7314733610425546
Enter a number (-1 to quit): 
299800000
The square root of 299800000 is 17314.733610425545
Enter a number (-1 to quit): 
0.0
The square root of 0.0 is 0.0
Enter a number (-1 to quit): 
four
four is not a number I understand.
Enter a number (-1 to quit): 
4
The square root of 4 is 2.0
Enter a number (-1 to quit): 
Enter a number (-1 to quit): 
(12)
(12) is not a number I understand.
-1

These results tell you a few things about the default number format on the platform where I ran it (U.S. English Windows NT, JDK 1.2rc1). First of all it doesn't understand exponential notation. The square root of 2.998E+8 is not 1.7314733610425546. It's 1.7314733610425546E+4. The number format parsed right up to the first character it didn't recognize (E) and stopped. Thus you got the square root of 2.998 instead. You can also see that this number format doesn't understand negative numbers represented by parentheses or words like "four". On the other hand, it can parse numbers with thousands separators like 2,345,678. This is more than the standard I/O libraries in most other languages can do. With the appropriate, non-default number format Java could parse (12), four, and 2.998E+8 as well.
Copyright 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 29, 2000