for (int i = 0; i < newBookCatalog.length; i++) {
double currentMin = newBookCatalog[i].getPrice();
int currentMinIndex = i;
for (int j = i + 1; j < newBookCatalog.length; j++) {
if (currentMin > newBookCatalog[j].getPrice()) {
currentMin = newBookCatalog[j].getPrice();
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
BookCatalog2 temp = newBookCatalog[currentMinIndex];
newBookCatalog[currentMinIndex] = newBookCatalog[i];
newBookCatalog[i] = temp;
}
}
//Display the newly sorted array of objects
for (int i = 0; i < newBookCatalog.length - 1; i++) {
System.out.printf("%-8d%-20s%-19s%-18.2f\n", newBookCatalog[i].getItemNumber(), newBookCatalog[i].getProduct(), newBookCatalog[i].getCategory(), newBookCatalog[i].getPrice());
}
break;
这是我到目前为止所拥有的。我试图通过提高价格来对数组进行排序,但是当程序运行时,它会显示除最后一项之外的所有项目。我重做了几次,但我无法得到显示最后一项的那种。我是初级水平,并从我的教科书和教师的帮助中复制了排序的基本结构。我的教科书中的例子只是针对一个int数组。所以这有点复杂。
任何提示或技巧?
答案 0 :(得分:1)
我重做了几次,但我无法得到显示最后的那种 项目
您通过newBookCatalog.length-1
排除最后一项,而应该是i < newBookCatalog.length
。
改变这个:
for (int i = 0; i < newBookCatalog.length-1; i++)
到此:
for (int i = 0; i < newBookCatalog.length; i++)