// Question 1 (corrected) from the intra of Fall 2004 class European { private String name; European(String name) { this.name = name; } } class Swiss extends European { int goldInKg; int bankAccounts=0; Swiss(String name, double goldInKg) { super("Swiss citizen:" + name); // the variable name is declared as private in the class European // and therefore is not accessible from outside this class, even // from Swiss which is one of its subclass // therefore instead of to trying to address name directly it is better // to call the constructor of the ancestor class //this.name = "Swiss citizen:" + name; this.goldInKg=(int)goldInKg; // an explicit cast from double to int is necessary or Java will worry // because of the possible loss of precision //this.goldInKg=goldInKg; } void openSwissBankAccount (int gold) throws MoreGoldException { if (gold > 10) { bankAccounts++; goldInKg += gold; } else { throw (new MoreGoldException()); // the valid keyword for throwing an exception is "throw" and not "throws" //throws(new MoreGoldException()); } } } class MoreGoldException extends Exception { MoreGoldException() { super("You need more gold to open a Swiss bank account!"); } } class TestEuropeans { public static void main(String args[]) { European s = new European("Norman"); // s should be declared as an European and not a Swiss and Java will not be happy during the // compilation :-) //Swiss s = new European("Norman"); Swiss s2 = new Swiss("William Tell",18.5); European e = (European) s2; s2.goldInKg++; // it is not possible to increase the value of goldInKg for e because the European class does not // have this variable //e.goldInKg++; // as the function openSwissBankAccount may throw an MoreGoldException, it is necessary to catch it try { s2.openSwissBankAccount(50); } catch (MoreGoldException excep){ System.out.print(excep);} } } class MathFunctions { public static int factorial(int x) // the function factorial should return an integer and therefore should not be declared as void //public static void factorial(int x) { if (x==0) // be careful not to confuse the symbol "==" which makes a comparison with the symbol "=" which // corresponds to an assignement and whose value is therefore always true if used in a IF statement //if (x=0) { return 1; } else { int val=1; for (int i=x; i>0; i--) // the loop should be stopped when zero is reached or the value returned will not be the factorial // but the value zero itself, therefore the stopping condition should be "i>0" and not "i>=0" //for (int i=x; i>=0; i--) { val *= i; // the expression "=*" is not a valid java symbol //val =*i; // there was a missing "}" in the code } return val; } } }