Using compareTo() to Get the Rank of a Name in Alphabetical Order - Example 5
Snippet: Using compareTo() to Get the Rank of a Name in Alphabetical Order
Explanation
This snippet uses compareTo() to compute the rank of "Mary" among the four names. The variable indexOfMary starts at 1, and for each name that comes before "Mary" (i.e. mary.compareTo(other) > 0), the rank is incremented.
"James" comes before "Mary", so indexOfMary becomes 2. "Michael" and "Patricia" both come after "Mary", so they do not increment the counter. The result is 2 — Mary is the second name in alphabetical order.
What You Can Do
Try computing the rank of "Michael" or "Patricia" using the same approach. Do the ranks of all four names together cover exactly 1, 2, 3, and 4?
You can also try adding a fifth name and updating the comparisons. Does the rank of "Mary" change?
Run it and observe the output!
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis