/* Basic Algorithms, Fall98, Fall99 (Yap) * file: Factorial1.java * * Variant of Factorial.java to illustrate * * -- a subtle issue of initialization of variables * -- the e.getMessage() method in exceptions * */ class Factorial1 { static int computeFactorial(int k) { if (k<0) return -1; else if (k == 0 || k == 1) return 1; else return k * computeFactorial(k-1); } public static void main(String[] args) { int n=0; // if you do not initialize n here, // the compiler will complain. Why? try{ n = Integer.parseInt(args[0]); // Reason: n is supposed to be initialized in // this try block which may not happen! } catch (Exception e){ System.out.println(e.getMessage()); // As it turns out, e.getMessage() returns 0 System.out.println("Error: argument must be integer"); return ; } for (int i = 0; i <= n; i++) System.out.println (i + " factorial is " + computeFactorial(i)); } }