import java.util.Scanner; /*******************************************************************************/ /** * This is an improved version that uses a main program to invoke a class * that contains the Newton code. The previous versions were done as simply * programs so as to concentrate on the loop structure and control of the flow * of execution. This would be a more proper Java version of such a program. * * @author Duncan Buell * 4 February 2008 **/ public class MySquareRootMain3 { public static void main (String[] args) { double epsilon,root,x; Scanner console = new Scanner(System.in); MySquareRoot rootFinder = new MySquareRoot(); // Notice how much code is involved just in getting the values input from the // user. There's a lot of effort that goes in to making sure that we are not // going to crash due to faulty input. Even at that, we have not tested to // make sure the user has actually input a ***number*** and not text characters. System.out.println("Enter the tolerance epsilon for successive approximations: "); epsilon = console.nextDouble(); if(epsilon <= 0) { System.out.println("ERROR: Input value " + epsilon + " for epsilon is not positive"); System.exit(0); } System.out.println("Enter the number for which to take the square root: "); x = console.nextDouble(); if(x <= 0) { System.out.println("ERROR: Input value " + x + " for x is not positive"); System.exit(0); } System.out.println("Compute the square root of " + x); System.out.println("Stop when the difference between successive approximations is < " + epsilon); // There's only one line of the 'do the work' part of the program. root = rootFinder.findRoot(x,epsilon); // And then there is a lot of output to make sure that humans understand what's been done. System.out.println("Approximate square root of " + x + " is " + root); System.out.println("Built in function says root of " + x + " is " + Math.sqrt(x)); System.out.println("The discrepancy is " + Math.abs(Math.sqrt(x) - root)); } } // public class MySquareRootMain3