University of Toronto - Fall 2000
Department of Computer Science
Week 8
- Loop Review - Student Example
Student.java
class Student {
private String name; // full name (family and given names)
/*
The name string consists of these parts, in order:
1) the family name, possibly including some (single) blanks
2) a double blank " " if necessary to separate the
family name from the given names
3) zero or more given names
4) maybe some trailing blanks
Only part (1) is required.
*/
// getFamilyName: return the family name.
// Only handles names of the form "CLARKE JIM"
public String getFamilyName () {
int pos = 0; // the character position we're
// currently looking at
String result = ""; // the family name we're
// building up
while (pos < name.length()) {
if (name.charAt(pos) == ' ') {
if (pos + 1 == name.length() ||
name.charAt(pos+1) == ' ') {
return result;
}
}
result += name.charAt(pos);
pos++;
}
return result;
}
}
TestStudent.java
// Test program to create a student object and print
// the student's family name.
public class TestStudent {
public static void main (String[] args) {
Student stu = new Student ("CLARKE JIM");
System.out.println ("Family name: >>>" +
stu.getFamilyName() + "<<<");
}
}
Output for TestStudent.java
Family name: >>>CLARKE<<<
TestStudent2.java - a better test class
// Test program to create various student objects with
// different names, and print the student's family name.
public class TestStudent2 {
public static void main (String[] args) {
String name = "CLARKE R JIM N ";
Student stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
name = "CLARKE JIM ";
stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
name = "CLA R JIM ";
stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
name = "CLA";
stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
name = "CLA ";
stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
name = " ";
stu = new Student (name);
System.out.println ("\nTesting: >>" + name + "<<");
System.out.println ("Family name: >>" +
stu.getFamilyName() + "<<");
}
}
Output for TestStudent2.java
Testing: >>CLARKE R JIM N <<
Family name: >>CLARKE R<<
Testing: >>CLARKE JIM <<
Family name: >>CLARKE<<
Testing: >>CLA R JIM <<
Family name: >>CLA R<<
Testing: >>CLA<<
Family name: >>CLA<<
Testing: >>CLA <<
Family name: >>CLA<<
Testing: >> <<
Family name: >><<