Hi im trying to write a program that sorts an array in alphabetical order and then into phone book order,

Eg input:
Jane Pascal 364756
Bob Smith 364758
Joe Bloggs 253647

The output should be:
Bloggs, Joe 253647
Pascal, Jane 364756
Smith, Bob 364758

The plan is to have each name (forename + surname) in different array's and the numbers in another and not sure how to sort them as above, any help would be great.

Dani AI

Generated

Storing names and numbers as separate parallel arrays makes keeping the data tied together fragile. For a clean, maintainable solution create a small Person object (first, last, phone), parse each input line into that object, collect them in a List<Person>, then sort the list. 's quick tokenization idea works for simple input; is right to point toward objects and comparators for real code — they let you sort by different keys without breaking the association between name and phone.

A robust parse approach is to treat the last whitespace-separated token as the phone and everything before it as the name. Split the name into tokens and take the first token as the forename and the last token as the surname (middle names are preserved in-between). This handles extra spaces and names with middle parts better than naive fixed-token parsing. If names themselves may contain spaces (prefixes, multi-word surnames) require a delimiter (comma, tab) instead.

Example workflow: parse each line into Person, implement a toString() that prints Last, First phone, then sort with a comparator that compares surname then forename, case-insensitively (or use a Collator for locale-aware ordering). Using objects keeps the phone number attached and makes future changes (secondary sort keys, different outputs) trivial. See the Java Comparator docs for comparator helpers and chaining: Comparator.

Recommended Answers

All 3 Replies

I would use the StringTokenizer to parse up the individual strings according to the spaces;

String foreName, surName, number;
 
StringTokenizer st = new StringTokenizer(str);
foreName = st.nextToken;
surName = st.nextToken;
number = st.nextToken;

then rearranging the strings

newStr = surName+", "+foreName+" "+number;

stick those into an array and then use the Arrays.sort

java.util.arrays.sort(stringArray);

Thanks, I new there was an Array.sort method just wasnt sure how to use it, cheers!

An even better way to do this would be to create a Person class with the appropriate fields, and create a new class that implements Comparator for each desired sort order. See .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.