// File: DynamicExample16.java // // Author: Rahul Simha // Created: Sept 2, 1998. // Modified: Sept, 2008 // // Doing a comparison externally. class Customer { String custName; int bankBalance; // A function to be called by all constructors: void setupData (String cname, int balance) { // ... test that cname is not null // and has valid chars ... custName = cname; // ... test that balance is positive // and within limits... bankBalance = balance; } public Customer (String cname, int balance) { setupData (cname, balance); } public Customer () { setupData ("XXXinvalidcustXXX", 0); } public Customer (String cname) { setupData (cname, 0); } public void printInterest (double percentageRate) { double interest = (percentageRate / 100) * bankBalance; System.out.println ("Customer " + custName + " gets " + interest + " dollars in interest"); } public String toString () { return ("Name=" + custName + ", Balance=" + bankBalance); } // Accessors public String getCustName () { return custName; } public int getBalance () { return bankBalance; } } public class DynamicExample16 { static int compare (Customer c1, Customer c2) { int b1 = c1.getBalance(); int b2 = c2.getBalance(); double ratio = (double) b1 / (double) b2; // Comparable if within same order of magnitude. if ( (0.1 < ratio) && (ratio < 10) ) return 0; else if (b1 < b2) return -1; else return 1; } public static void main (String[] argv) { Customer c1 = new Customer ("Bill G", 1000000); Customer c2 = new Customer ("Larry E", 100000); int comp = compare (c1, c2); if (comp < 0) System.out.println ("c2 is richer"); else if (comp > 0) System.out.println ("c1 is richer"); else System.out.println ("same balance"); } }