prognatis
prognatis

Reputation: 33

Java (beginner): Displaying the first name alphabetically and last name alphabetically after being given a list of names from the user

I've been working on a problem:

"Design a program that asks the user for a series of names (in no particular order). After the final person’s name has been entered, the program should display the name that is first alphabetically and the name that is last alphabetically.

For example, if the user enters the names Kristin, Joel, Adam, Beth, Zeb, and Chris, the program would display Adam and Zeb."

I have a function called getString, which returns a valid string input; and a module called displayResults, which displays the first name alphabetically, and last name alphabetically. I also use "q" as a sentinel value to exit the while loop.

However, I am running into a problem where if I enter in names such as: "bob", "david", "alex", and "charlie", it will display the first name correctly as "alex", but will display the last name incorrectly as "charlie" instead of "david". I've tried looking through my code for an error, but wasn't able to locate where it's messing up. Any help is appreciated.

name = getString("Please enter a name, or input q to exit.");

if(!name.equals("q")) {
   low = name;
   high = name;
}

while(!name.equals("q")) {
   int x;
   x = name.compareToIgnoreCase(low);
   if(x == -1){
      low = name;
   }
   x = name.compareToIgnoreCase(high);
   if(x == 1) {
      high = name;
   }
   name = getString("Please enter another name, or input q to exit.");
}

displayResults(low, high);

Upvotes: 0

Views: 1470

Answers (3)

In order to sort names you should use a collection that sorts the elements as you put them in.
For this porpose you can use the TreeSet implementation which is a sorted Set. Set also makes sure that no repeating elements are stored (for this it uses the compareTo method of the elements).

Also you can create a Collator object (which implements the comparator interface), which can use a locale object to sort the elements. It's easy to do localization based sorting with this method.

Please see the example below:

public static void main(String[] args) {
    // Create the locale object
    // This will be used when sorting the elements
    Locale myLocale = Locale.ENGLISH;
    // Locale myLocale = new Locale("HU", "hu");
    // Locale myLocale = Locale.getDefault();

    // Create the collator which will be responsible for using the locale object in order to compare the elements in the TreeSet
    Collator coll = Collator.getInstance(myLocale);
    coll.setStrength(Collator.PRIMARY);

    // TreeSet for storing the elements
    // Note that the TreeSet is instantiated with the collator object
    TreeSet<String> names = new TreeSet<>(coll);
    names.add("bob");
    names.add("david");
    names.add("alex");
    names.add("charlie");

    // You can call first and last method to get the first and last element sorted
    System.out.println(names.first());
    System.out.println(names.last());
}

I think this is the easiest, fastest, and most professional way of sotring elements since in this case you let java do the sorting for you, you only need to configure the way it should do it.

I hope this will be useful.

Upvotes: 0

Luis Michaelis
Luis Michaelis

Reputation: 60

You could use a List which you sort then.

import java.util.List;
import java.util.Collections;

public class Main {
    public static void main (String[] args) {
        boolean run = true;
        List<String> names = new List<String>();
        while (run) {
            String name = getString ();
            if (name == "q") run = false;
            else
                names.add (name);
        }
        Collections.sort (names);
        // Results:
        System.out.println (names.get (0)); // Print out first entry
        System.out.println (names.get (names.size() - 1)); // ... and last one
    }

    public static String getString () {
        // Your method
    }

}

Upvotes: 0

Scott Shipp
Scott Shipp

Reputation: 2301

The Java API documentation only states that compareToIgnoreCase() "Returns: a negative integer, zero, or a positive integer". Since you are comparing x to 1 and -1 respectively it is possible you are actually receiving another value back and therefore the true "high" is not being detected.

Another possibility is that there may be invisible characters (like space or return) in your input. When I ran " david".compareToIgnoreCase("charlie") on my machine here it returned -67.

Upvotes: 4

Related Questions