I'm working on an exchange sort for an ArrayList of objects so that it can be sorted ascending depending on the value in the object. When I compile it, everything works great until the last element is not sorted properly. I suspect that the problem is with the iterator. I tried many combinations but it won't sort properly. Also, I can't use sort() or any prebuilt libraries. I'd appreciate any guidance!
void sortAndDisplay (ArrayList<Car> cars) {
Car temp;
for (int i = 0; i < cars.size() -1; i++) {
for (int j = i+1; j < cars.size(); j++ ) {
if (((cars.get(i).getMake()).compareToIgnoreCase(cars.get(j).getMake()) > 0)) {
temp = cars.get(i);
cars.set(i, cars.get(j));
cars.set(j, temp);
}
}
}
for (int i = 0; i < cars.size(); i++) {
System.out.print(cars.get(i)+"\n\n");
}
}
The Car class:
public class Car {
String make;
String model;
public Car (String make,
String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
The method I used to read the values from the file:
ArrayList<Car> readCars(FileReader file) throws Exception {
String arr[] = {};
String line = "";
BufferedReader scan = new BufferedReader(file);
ArrayList<Car> carsArr = new ArrayList<Car>();
while ((line = scan.readLine()) != null) {
arr = line.split(",");
Car car = new Car(arr[0], arr[1]);
carsArr.add(car);
}
System.out.println("The file was read.");
return carsArr;
}
java has sorting built in:
void sortAndDisplay (List<Car> cars) {
cars.sort(Comparator.comparing(Car::getMake));
System.out.println(cars.stream().collect(Collectors.joining("\n\n")));
}
I created the file x.txt
with the following data:
WERTfgd, bmw
ETRHFDdfgsdf, bmw
ewrd, bmw
HTfgdfgs, bmw
dDSFSfgd, bmw
ter, bmw
jhvbn, bmw
Frqw, bmw
I copied your code literally by adding getMake()
into this System.out.print (cars.get (i).getMake () + "\ n \ n");
in order to get the wanted output...
dDSFSfgd
ETRHFDdfgsdf
ewrd
Frqw
HTfgdfgs
jhvbn
ter
WERTfgd
Which is correct, so I can't figure out what's your problem.
Maybe you are not sure how the method compareToIgnoreCase()
works?
Tried your code with short example list and it worked. Could you give a failing example input with corresponding output?
BTW I recommend adding a toString()
method to the Car
class. For example:
@Override
public String toString() {
return "<Car<" + make + "><" + model + ">>";
}
With that printing the list of cars can be done like:
System.out.println(cars);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.