/** * Demonstrates the differences in scope and lifetime of variables. * * @author Pete Nordquist * @version 061019 */ public class W04N03 { // 'global' scope -- visible to all methods // these example variables are used for error checking in the methods below private static final double MAXINPUT = 5; private static final double MAXRESULT = 200.0; public static void main(String[] args) { // d1 and d2 have local scope // visible from the point they are defined to the closing brace // that ends the block in which they were defined. double d1 = IO.readDouble("1st Num? "); // turn d1 non-negative d1 = Math.abs(d1); // if d1 is too big if (d1 > MAXINPUT) // print an error System.err.println("d1, " + d1 + ", is too big." + " Max allowable is " + MAXINPUT); else { // read d2 double d2 = IO.readDouble("2nd Num? "); // turn d2 positive d2 = Math.abs(d2); // if d2 is too big if (d2 > MAXINPUT) // print an error System.err.println("d2, " + d2 + ", is too big." + " Max allowable is " + MAXINPUT); else { // calculate result double result = calculatePowers(d1, d2); if (result != 0) System.out.println("result is " + result); } } } /** * x and y have 'parameter' scope -- they are visible in calculatePowers() * but not in main() * calculatePowers checks its result and prints an error if it is too big * and returns 0 in this case * @return the value x raised to the y power. */ public static double calculatePowers(double x, double y) { // result has 'local' scope double result; // call the pow method in the Math class result = Math.pow(x, y); if (result > MAXRESULT) { System.err.println("calculatePowers result, " + result + " is too big."); result = 0; } // finish the method and pass the value in the memory location // named result back to the call site. return result; } }