У меня есть код для выполнения сортировки вставкой (по возрастанию или по убыванию, в зависимости от параметра) на основе названия класса Movie2. Ниже приведен код метода main и метода sortTitles, в котором метод printMovies печатает элементы массива.
public static void main (String [] args)
{
Movie2[] myMovies = {new Movie2 ("The Muppets Take Manhattan",2001,"Columbia Tristar"),new Movie2 ("Mulan Special Edition",2004,"Disney"),new Movie2 ("Shrek 2",2004,"Dreamworks"),new Movie2 ("The Incredibles",2004,"Pixar"),new Movie2("Nanny McPhee",2006,"Universal"),new Movie2 ("The Curse of the Were Rabbit",2006,"Aardman"),new Movie2 ("Ice Age",2002,"20th Century Fox"), new Movie2 ("Lilo & Stitch",2002,"Disney"), new Movie2("Robots",2005,"20th Century Fox"), new Movie2("Monters Inc.", 2001, "Pixar")};
System.out.println("Before Sorting:");
printMovies(myMovies);
System.out.println();
System.out.println("Sorted by Title - ascending: ");
myMovies = sortTitles(myMovies,1);
printMovies(myMovies);
}
public static Movie2[] sortTitles (Movie2[] movies, int asc)
{
if (asc == 2)
{asc = 0;}
for (int index = 1; index < movies.length; index+=1)
{
int other = index - 1;
Movie2 movie = movies[index];
int first = (int) movies[index].getTitle().toLowerCase().charAt(0);
int second = (int) movies[other].getTitle().toLowerCase().charAt(0);
for (other = index - 1; other >= 0 && (((first < second) ? 1 : 0) == asc); other-=1)
{
movies[other+1] = movies[other];
}
movies[other+1] = movie;
}
return movies;
}
Однако результат, который я получаю, выглядит так:
Before Sorting:
The Muppets Take Manhattan, 2001, Columbia Tristar
Mulan Special Edition, 2004, Disney
Shrek 2, 2004, Dreamworks
The Incredibles, 2004, Pixar
Nanny McPhee, 2006, Universal
The Curse of the Were Rabbit, 2006, Aardman
Ice Age, 2002, 20th Century Fox
Lilo & Stitch, 2002, Disney
Robots, 2005, 20th Century Fox
Monsters Inc., 2001, Pixar
Sorted by Title - ascending:
Monsters Inc., 2001, Pixar
Robots, 2005, 20th Century Fox
Lilo & Stitch, 2002, Disney
Ice Age, 2002, 20th Century Fox
Nanny McPhee, 2006, Universal
Shrek 2, 2004, Dreamworks
Mulan Special Edition, 2004, Disney
The Muppets Take Manhattan, 2001, Columbia Tristar
The Incredibles, 2004, Pixar
The Curse of the Were Rabbit, 2006, Aardman
Хотя некоторые фильмы отсортированы по названию, другие нет. Когда я компилирую и запускаю программу, ошибок не возникает, и я не могу понять, в чем проблема моей логики. Любая помощь будет оценена по достоинству.
Обновлено: добавление кода класса Movie2.
public class Movie2
{
// instance variables - replace the example below with your own
private String title, studio;
private int year;
/**
* Constructor for objects of class Movie2
*/
public Movie2(String title, int year, String studio)
{
// initialise instance variables
this.title = title;
this.year = year;
this.studio = studio;
}
public String toString()
{
return this.title + ", " + this.year + ", " + this.studio;
}
public String getTitle()
{
return this.title;
}
public void setTitle(String titleSet)
{
this.title = titleSet;
}
public String getStudio()
{
return this.studio;
}
public void setStudio(String studioSet)
{
this.studio = studioSet;
}
public int getYear()
{return this.year;}
public void setYear (int yearS)
{this.year = yearS;}
}
Почему вы использовали .charAt(0); и сравнили первые символы названий?
@statut Мое задание - отсортировать массив по первой букве заголовка. Я сравниваю заголовки, чтобы увидеть, какой элемент в массиве должен стоять перед другим.
Вы сравниваете фильм с предыдущим, затем перемещаете фильм ** в начало ** (?), Если фильм меньше предыдущего. Вам также необходимо обновить значение second внутри цикла.
@Andreas, когда мне переместить фильм в начало? Спасибо за совет second, который немного помог, но все еще не работает.




Вместо этого внутренний цикл for можно было бы переписать следующим образом:
while (other >= 0 && (((first > second) ? 1 : 0) == asc)) {
movies[other+1] = movies[other];
other = other - 1;
if (other >= 0) {
second = (int) movies[other].getTitle().toLowerCase().charAt(0);
}
}
Проблема в том, что значение переменной second никогда не обновлялось, чтобы указывать на первую букву заголовка проверяемого элемента.
Вот полный код sortTitles с измененным только внутренним для:
public static Movie2[] sortTitles(Movie2[] movies, int asc) {
if (asc == 2) {
asc = 0;
}
for (int index = 1; index < movies.length; index += 1) {
int other = index - 1;
Movie2 movie = movies[index];
int first = (int) movies[index].getTitle().toLowerCase().charAt(0);
int second = (int) movies[other].getTitle().toLowerCase().charAt(0);
while (other >= 0 && (((first > second) ? 1 : 0) == asc)) {
movies[other + 1] = movies[other];
other = other - 1;
if (other >= 0) {
second = (int) movies[other].getTitle().toLowerCase().charAt(0);
}
}
movies[other + 1] = movie;
}
return movies;
}
Спасибо, это работает, когда asc = 1! Однако он выдает исключение ArrayOutOfBoundsException, когда asc = 2, не знаю почему.
Это вызывает исключение, потому что other равно -1 в строке second = (int) movies[other]..., знаете ли вы, почему это могло произойти?
Да. Это происходит в том случае, когда other равен 0 внутри цикла while, что вызывает проблему -1. Я отредактировал свой ответ и добавил проверку if, которая должна предотвратить это.
выбросьте код и напишите правильный объектно-ориентированный код с помощью Comparator