从文件中读取并选择按价格对存储的对象数组进行排序不起作用

我真的被困在这里,我不知道为什么我得到了错误的选择排序列表。我将 Pencilbox 对象存储在两个不同的数组中,在其中一个数组中我必须按价格对数组进行排序。按价格排序没有按预期工作,我尝试了很多方法来修复它,但仍然不起作用。这是我从中提取信息的文本文件-(每个参数如下:铅笔盒的高度、宽度、价格)


12,1,1.49

10,2,2.59

8,1,1.23

3,3,3.33

12,1,1.49

6,2,3.50

10,2,2.59

11

8,2,4.00

7,2,3.00

7,3,1.49

11,2

4,2,2.34

14,2,6.99

10,2,2.59

8,1,2.35

//铅笔盒的高度、宽度、价格


我得到这个输出:


12, 1, 1.49

7, 3, 1.49

8, 1, 1.23   <=== 1.49 > 1.23 so that's incorrect

12, 1, 1.49

8, 1, 2.35

4, 2, 2.34   <=== this one's the same, 2.34 < 2.35

10, 2, 2.59

10, 2, 2.59

10, 2, 2.59

7, 2, 3.0

3, 3, 3.33

6, 2, 3.5

8, 2, 4.0

14, 2, 6.99

基本上,代码位于三个不同的文件中,但我在这里将它们组合起来。我标记了发生分离的区域。如果格式看起来有问题,我真的很抱歉,我已尽力修复它。我很感激任何反馈



Smart猫小萌
浏览 48回答 1
1回答

ITMISS

在 SelectionSort() 方法中,内部for j循环应仅用于查找最低索引,并且应在内部循环完成后进行值的交换for j:for (int i = 0; i < length - 1; i++) {&nbsp;&nbsp; &nbsp; int indexLowest = i;&nbsp;&nbsp; &nbsp; for (int j = i + 1; j < length; j++) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (array[indexLowest].getPrice() > array[j].getPrice()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; indexLowest = j;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; Pencilbox temp = array[i];&nbsp; &nbsp; array[i] = array[indexLowest];&nbsp; &nbsp; array[indexLowest] = temp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java