2

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

}
4
  • Thanks Ted Hopp. That was awesome. Commented Oct 23, 2012 at 0:45
  • I think he/she wants to alphabetize the list, and it's not working. Commented Oct 23, 2012 at 0:46
  • Have you tried java.util.Collections.sort? (I am not if it works for ArrayLists, but it works for Lists with Strings) Commented Oct 23, 2012 at 0:46
  • No the list was all ready alphabetized before i just need to make sure the object that i add goes in proper place. Commented Oct 23, 2012 at 0:46

4 Answers 4

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This code still adds the car object to the top of the ordered list. Not sure what is the problem
I've added an example and updated the original post. If you're still having issues, I need to see the code you're using
2

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.