【发布时间】:2019-08-07 02:47:21
【问题描述】:
SOF。我有一个问题,我遇到了一些困难。
下面的代码应该逐行筛选文件,有效地利用 StringTokenizer 来获取 Car 类的 Make、Model、Year 和 Mileage(按此顺序)并将它们存储在汽车对象中,然后我添加到 2 个 ArrayList,其中一个由 Make“排序”,另一个是“未排序”。
我编写的 selectionSort 最初使用字符串,但由于明显的原因无法正常工作。
可以通过使 selectionSort 与对象(汽车)一起工作来解决这个问题吗? Eclipse 向我推荐了它,而当前的 selectionSort 就是它的产物。
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;
}
}
任何帮助将不胜感激。
【问题讨论】:
标签: java sorting arraylist selection-sort