gpt4 book ai didi

java - SelectionSort 方法将按类型对 ArrayList 进行排序

转载 作者:行者123 更新时间:2023-11-30 01:53:40 25 4
gpt4 key购买 nike

SOF。我有一个问题,我遇到了一些困难。

下面的代码应该逐行筛选文件,有效地利用 StringTokenizer 来获取汽车类的品牌、型号、年份和里程(按顺序)并将它们存储在汽车对象中,该对象然后我添加到 2 个 ArrayList,其中一个通过 Make“排序”,另一个“未排序”。

我编写的选择排序最初适用于字符串,但由于明显的原因而不起作用。

可以通过使选择排序与对象(汽车)一起使用来解决这个问题吗? Eclipse 向我推荐了这一点,当前的选择排序就是它的产物。

public void readFile(String file) throws FileNotFoundException //an object array that takes in string files
{
try {
File myFile = new File(file); //converts the parameter string into a file
Scanner scanner = new Scanner(myFile); //File enables us to use Scanner
String line = scanner.nextLine(); //reads the current line and points to the next one
StringTokenizer tokenizer = new StringTokenizer(line, ","); //tokenizes the line, which is the scanned file

int tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens
while (tokenizer.hasMoreTokens()){
if(tokenCount > 4) {
System.out.println(" Not 4 tokens");
}
else {
String CarMake = tokenizer.nextToken(); //since car is in order by make, model, year, and mileage
String CarModel = tokenizer.nextToken();
int CarYear1 = Integer.parseInt(tokenizer.nextToken());
int CarMileage1 = Integer.parseInt(tokenizer.nextToken()); //converts the String numbers into integers
Car cars = new Car(CarMake, CarModel, CarYear1, CarMileage1); //since the car has a fixed order
arraylist.add(cars); //add the cars to the unsorted array
}
}
scanner.close(); //close the scanner
} catch (FileNotFoundException f){
f.printStackTrace();
}
arraylist2.addAll(arraylist);
selectionSort(arraylist2);
}

public static void selectionSort(ArrayList<Car> arraylist) //Selection sort using strings
{
for (int i = 0; i <= arraylist.size(); i++)
{
// Look through the unsorted strings (those at j or higher) for the one that is first in order
int min = i;
for (arraylist[i].getMake.compareTo(arraylist[min].getMake) < 0) { //use the inherent string compareTo
min = k;
}
String temp = arraylist[i].getMake; //swapping
arraylist[i].getMake = arraylist[min].getMake;
arraylist[min] = temp;
}
}

任何帮助将不胜感激。

最佳答案

您的新代码不起作用的原因是您只交换了汽车的品牌,而不是完整的 Car 对象。

应该是:

Car temp = arraylist[i]; //swapping
arraylist[i] = arraylist[min];
arraylist[min] = temp;

关于java - SelectionSort 方法将按类型对 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com