簡體   English   中英

將對象添加到按字母順序排列的數組中

[英]Adding objects into alphabetically ordered array List

此代碼要求用戶輸入具有名稱,型號年份,上市價格和折扣百分比的車輛對象。 這里出現的問題是,當用戶輸入以上所有信息時,汽車對象被添加到數組列表的底部而不是按字母順序。 請注意,列表之前已按字母順序排列。

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

}

found的變量在初始化后永遠不會改變,因此while循環總是到達列表的末尾。

雖然稍微偏離主題,但您可以使用Collections.binarySearch來確定應插入新值的位置...

來自Java Docs

返回:搜索鍵的索引(如果它包含在列表中); 否則,( - (插入點) - 1)。 插入點定義為鍵將插入列表的點 :第一個元素的索引大於鍵,或者list.size(),如果列表中的所有元素都小於指定的鍵。 請注意,當且僅當找到密鑰時,這可以保證返回值> = 0。

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);

這假設Proj1CarDataComparableProj1CarData你將需要提供自己的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);

更新

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);
}

我無法清楚地看到你的問題。 我猜你得到“字母順序”的算法存在一些邏輯上的錯誤。

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

        }

在此循環之后,loc的值將由carList.size添加,因​​為if()中的條件始終為true。 這意味着您將始終將newCar添加到arrayList的末尾,但不是以您想要的正確順序。

實現Comparator接口可能會有所幫助。

搞定了。 我用對象遍歷了數組列表。 從鍵盤輸入的名稱在“if”語句中用作compareToIgnoreCase()方法的條件。 它將該對象添加到按字母順序排列的數組列表的正確位置。

     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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM