University of Toronto - Fall 2000
Department of Computer Science

Week 6 - Name class

Version 3

Create a static variables in the Name class that can be used to show the average length of all Names created from this class.

// Describe objects that have a first and last name, and an optional 
// middle name.
class Name {
	private String first;	  	// First name
	private String middle; 	// Middle name, or null if none
	private String last;	  	// Last name

	private static int numNames = 0;	// Number of Names created
	private static int totalLength = 0; 	// Total length of all Names

	// Make me with first name f, last name l, and no middle name.
	public Name (String f, String l) {
		this.first = f;
		this.last = l;
		totalLength += (this.first+this.last).length();
		numNames++;
	}

	// Make me with first name f, middle name m, and last name l.
	public Name (String f, String m, String l) {
		this(f, l);		// calls the other constructor
		this.middle = m;
		totalLength += (this.middle).length();
	}

	// Return my first, middle, last names as a String.
	public String toString() {
		String result = this.first;
		if (this.middle != null) {
			result = result + " " + this.middle;
		}
		result = result + " " + this.last;
		return result;
	}

	// Return average name length
	public static double getAveLength() {
		return (double)totalLength/numNames;
	}

	// Return true if my names are the same as
	// n's, false otherwise.
	public boolean equals (Name n) {
		return this.first.equals (n.first) &&
		this.last.equals(n.last) &&
		equals(this.middle, n.middle);
	}

	// Return true if both s1 and s2 are null, or if
	// s1 and s2 have the same contents.
	private static boolean equals (String s1,String s2){
	   	return (s1 == null && s2 == null) ||
		   	(s1 != null && s1.equals(s2));
	}

	public static void test () {
		Name n1 = new Name ("Fred", "Smith");
		Name n2 = new Name ("Jane", "Amy", "Doe");
		System.out.println ("Average name length: " + Name.getAveLength());
		n1 = new Name ("Jim", "Edward", "Banks");
		System.out.println ("Average name length: " + Name.getAveLength());
	}

	public static void main (String[] args) {
		Name.test();
	}
}

Output:

Average name length: 11.0