// 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
// 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;
}
// Make me with first name f, middle name m, and last name l.
public Name (String f, String m, String l) {
this.first = f;
this.middle = m;
this.last = l;
}
// 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 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 && s2 != null && s1.equals(s2));
}
// Test two names for equality. If they're
// different, print an error message.
public static void testSame (Name n1, Name n2) {
if (! n1.equals(n2) ) {
System.out.println ("Test failure: " + n1 +
" " + n2 + " " + n1.equals(n2));
}
}
// Test two names for equality. If they're
// the same, print an error message.
public static void testDiff (Name n1, Name n2) {
if ( n1.equals(n2) ) {
System.out.println ("Test failure: " + n1 +
" " + n2 + " " + n1.equals(n2));
}
}
// Test names with/without a middle name.
public static void test () {
// Test same names, no middle.
testSame( new Name("A","B"), new Name("A","B") );
// Test different names, no middle.
testDiff( new Name("A","B"), new Name("A","C") );
testDiff( new Name("A","B"), new Name("C","B") );
testDiff( new Name("A","B"), new Name("B","A") );
// Test same names, with middle.
testSame( new Name("A","B","C"), new Name("A","B","C") );
// Test different names, no middle.
testDiff( new Name("A","B","C"), new Name("D","B","C") );
testDiff( new Name("A","B","C"), new Name("A","D","C") );
testDiff( new Name("A","B","C"), new Name("A","B","D") );
// Test different names, first with no middle.
testDiff( new Name("A","C"), new Name("A","B","C") );
// Test different names, second with no middle.
testDiff( new Name("A","B","C"), new Name("A","C") );
}
}
Simple test class to run the test method, which tests our Name class. This could have been included in the Name class instead.
public class RunTest {
public static void main (String[] args) {
Name.test();
}
}
No output.