Nic
Nic

Reputation: 73

Adding objects into alphabetically ordered array List

This code asks user to enter vehicle object that has name, model year, listing price, and percent Discount. The problem that is occurring here, when user enters all of the above info the car object is added to the bottom of the array list and not in the alphabetical order. Note the list was alphabetized before.

while (!valid) {
    String str = scan.nextLine();
    try {
        boolean found = false;
        System.out.println("Enter car name: ");
        name = scan.nextLine();
        System.out.println("Enter car model year: ");
        modelYear = scan.nextLine();
        System.out.println("Enter car list price: ");
        listPrice = scan.nextDouble();
        System.out.println("Enter car percent discount: ");
        percentDiscount = scan.nextDouble();

        int i = 0;
        loc = 0;
        while (!found && i < carList.size()) {
            String nameRetrievedFromCarList = carList.get(i).getName();
            String nameToAdd = "";
            if (nameToAdd.compareToIgnoreCase(nameRetrievedFromCarList) < 0) {
                loc++;
                found = true;

            }
            i++;

        }// end while

        Proj1CarData newCar = new Proj1CarData(name, modelYear, listPrice, percentDiscount,
                discountAmount, netPrice);
        carList.add(loc, newCar);

        valid = true;

    }// end try

    catch (NumberFormatException nfe) {
        System.out.println("Wrong entry:  Try again");
    }// end catch

}

Upvotes: 2

Views: 7846

Answers (4)

Nic
Nic

Reputation: 73

Got it working. I traversed the array list with objects. The name entered from keyboard was used inside "if" statement as a condition with compareToIgnoreCase() method. It adds that object in proper location of alphabetically ordered array list.

     while(!valid)
      {
       try
          {

           System.out.println("Enter car name: ");
           name = scan.nextLine();
           System.out.println("Enter car model year: ");
           modelYear = scan.nextLine();
           System.out.println("Enter car list price: ");
           listPrice = scan.nextDouble();
           System.out.println("Enter car percent discount: ");
           percentDiscount = scan.nextDouble();

           for (int i = 0; i < carList.size(); i++) {
              String nameRetrievedFromCarList = carList.get(i).getName( );

              if (name.compareToIgnoreCase(nameRetrievedFromCarList) < 0) {
                 break;
              }
              loc++;
           }

           discountAmount = listPrice * percentDiscount/100.0;
           netPrice = listPrice - discountAmount;

           Proj1CarData newCar = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);

           carList.add(loc, newCar);

           valid = true;




        }//end try


           catch(NumberFormatException nfe)
           {
              System.out.println("Wrong entry: it is not an Integer! Try again");
           }//end catch

     }//end while

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347314

While slightly off topic, you could use Collections.binarySearch to determine where the new value should be inserted...

From the Java Docs

Returns: the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

Proj1CarData newCar = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);

int index = Collections.binarySearch(carList, newCar);
if (index < 0) {
    index = (index * -1) - 1;
}

carList.add(index, newCar);

This assumes that Proj1CarData is Comparable, other wise you will need to supply your own Comparator

Proj1CarData newCar = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);

int index = Collections.binarySearch(carList, newCar, 
    new Comparator<Proj1CarData>() {
        public int compare(Proj1CarData car1, Proj1CarData car2) {
            return car1.getName().compareToIgnoreCase(car2.getName());
        }
    });

if (index < 0) {
    index = (index * -1) - 1;
}

carList.add(index, newCar);

UPDATED

List<String> names = new ArrayList<String>(25);
names.add("Hurzdiirn");
names.add("Alydriira Talabdiira");
names.add("Urlidil Sineth");
names.add("Quavyraen Belarral");
names.add("Belarayne'bryn Agh'Quarbryn");
names.add("Alakgos");
names.add("Sszoj'hrae Laelraema");
names.add("Szornet");
names.add("Filojafay");
names.add("Lltril'net Chaszhrae");

Collections.sort(names);

for (int index = 0; index < names.size(); index++) {
    String name = names.get(index);
    System.out.println("[" + index + "] " + name);
}

int insertAt = Collections.binarySearch(names, "Luke");
if (insertAt < 0) {
    insertAt = (insertAt * -1) - 1;
}

names.add(insertAt, "Luke");

for (int index = 0; index < names.size(); index++) {
    String name = names.get(index);
    System.out.println("[" + index + "] " + name);
}

Collections.sort(names);
for (int index = 0; index < names.size(); index++) {
    String name = names.get(index);
    System.out.println("[" + index + "] " + name);
}

Upvotes: 3

feikiss
feikiss

Reputation: 354

I cannot catch what your question clearly. I guess there is some logical wrong about the algorithm you get the "alphabetical order".

while (!found && i < carList.size()) {
            String nameRetrievedFromCarList = carList.get(i).getName();
            String nameToAdd = "";
            if (nameToAdd.compareToIgnoreCase(nameRetrievedFromCarList) < 0) {
                loc++;
            }
            i++;

        }

after this loop, the value of loc will be added by carList.size because the condition in the if() is always true. That means you will always add the newCar to the end of the arrayList but not in the correct order you want.

Implementing Comparator interface may can help.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49893

The variable found is never changed after being initialized, so the while loop always goes to the end of the list.

Upvotes: 2

Related Questions