/* Java class whose only purposes are to test the SquareRootCalc class and to illustrate exception handling. */ //import java.io.*; import java.io.IOException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.BufferedReader; import java.text.NumberFormat; import java.util.Scanner; public class SqRootDriver { public static void main(String[] args) throws IOException { Scanner keyboard = new Scanner(System.in); File f = new File("junk.txt"); BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); //new BufferedReader(new InputStreamReader(f)); } catch (FileNotFoundException e) { System.out.println("There is no file of the specified name."); System.out.println("Program aborting."); System.exit(1); } NumberFormat nf = NumberFormat.getInstance(); SquareRootCalc s = new SquareRootCalc(); String response = br.readLine(); while (response != null) { System.out.println("Next input = " + response); //System.out.println("Hit enter"); //keyboard.nextLine(); try { // next line could cause a NumberFormatException to be thrown long n = Long.parseLong(response); // next line could cause an IllegalArgumentException to be thrown long sqrtOfn = s.sqrt(n); System.out.println("floor of square root of " + n + " is " + nf.format(sqrtOfn)); if (squareOf(sqrtOfn) <= n && squareOf(sqrtOfn+1) > n) { // answer is correct, so do nothing } else { System.out.println("ERROR: Wrong answer!!"); } } catch (NumberFormatException e) { System.out.println("Your input was not an integer, you idiot!"); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } finally { System.out.println(); } // read next input response = br.readLine(); } // while } // main private static long squareOf(long k) { return k*k; } }