Next: Part Two
Up: Part One
Previous: Send in the second
Let's write a method that gets things right.
- 1.
- Write a new method called compareNames that takes
two Strings as arguments and that returns an integer, -1 if
the first name precedes the other in the alphabet, 1 if it
succeeds the other, and 0 if the names are the same.
- 2.
- One of the things you will have to do is separate the name
into firstName and lastName. You may assume that the name will
contain only two words, separated by exactly one space. You can
find the position of the space using indexOf, and extract
the first and last names using substring.
- 3.
- Once you have the two names, you will want to convert them
to lower case (or upper case) and then compare them. If the
last names are the same, you will have to use the first names to
make the decision. Make sure you test this part of your program
by giving it two names with the same last name (maybe yours and
a sibling's).
NOTE REGARDING THE READING: In the book, they write a method
called compare that takes two Strings as arguments.
This is different from the built-in method called compareTo
that gets invoked on one String, and receives the second String
as an argument.
Neither way of writing a method is necessarily better than the
other, although there are tradeoffs that we will get to later.
But for now you should be aware of the difference, and know how
to invoke either one.
Next: Part Two
Up: Part One
Previous: Send in the second
Allen B. Downey
3/11/1998