// Example of program with a main method and class method nthRoot import java.io.*; class Week2A { // define the identifiers with class scope. See page 202, section 6.7 static BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in)) ; static PrintWriter screen = new PrintWriter( System.out, true); //--------Class methods start here------------------------------- private static double nthRoot(double x, double n) { //------------------------------------------------------- // This class method finds the nth root of any real number // ------------ // i.e this is a 'method'( see page 28) built into the class Week2A // It is the convention to have all the class methods defined before the main method. // see page 229 . This method is only visible from the class Week2A. // This is a choice I have made..I could, if I wish, make it visible from // any class by using 'public'. double logofanswer; // warning: this method is unprotected against x <= 0 ( for notation see Fig 3.2) logofanswer = Math.log(x)/n; return Math.exp(logofanswer); } //------------------------------------------------------- // You could add more class methods here... // private static ......etc... // { // java code // java code // ditto // } //------------ End of class methods -------------------------- public static void main (String [] args ) throws IOException { String name; screen.print( "Please type in your name ?" ); screen.flush(); name = keyboard.readLine(); screen.print ("\n\nHello " + name ); screen.println(" - This week.. an example of a class method\n\n"); screen.println(" The cube root of 27 = " + nthRoot(-27,3)); screen.println(" The cube root of 9*9*9 = " + nthRoot(9*9*9,3)); screen.println(" The 3/2 root of 9*9*9 = " + nthRoot(9*9*9,1.5)); // notice from the output, computers work to a finite accuracy with real numbers // QUESTION. Does the following line produce the right answer?If not, why not? // screen.println(" The 3/2 root of 9*9*9 = " + nthRoot(9*9*9,3/2)); // the main method ends here so program stops when it reaches this point. } }