首页 > 解决方案 > 创建与 ArrayList 一起使用的冒泡排序方法时遇到问题

问题描述

试图为我的 java 1 类创建一个电影管理器,但我无法弄清楚如何让冒泡排序方法与数组列表一起使用。arraylist 包含的元素,(String name, String genre, String actor, int year)我希望能够按我想要的任何元素对其进行排序。我使用 switch 语句来提示用户想要对其进行排序,然后我将使用重载方法来搜索,具体取决于我发送它的元素。

我尝试在网上查找一堆类似的代码并使用对他们有用的代码,但我一直遇到问题,我不完全确定在哪里。实际上,我认为我有一些问题,但我不知道如何解决它们。

public void bubbleSort(ArrayList movieList)
{
    movieList temp;
    for (int i = 0; i < movieList.size(); i++)
    {
        for (int j = 1; j < (movieList.size() - i); j++)
        {
                if (this.movieList.get(i).getName().compareToIgnoreCase(String.valueOf(i - 1)) > 0)
                {
//                  System.out.println("Movie found : %s%n", this.movieList);
                    temp = movieList.get(i);
                    movieList.set(i, movieList.indexOf(i-1));
                    movieList.indexOf(i-1) = temp;
                }

        }
    }
}

我只需要对数组进行排序的方法,然后将其显示给用户(我已经可以将其显示回来)。

*编辑继承人我到目前为止的完整代码

电影管理器类

import java.util.Scanner;
public class MovieManager {
    static Scanner stdin = new Scanner(System.in);
    public static void main(String[] args)
    {
        //        Movie movie = new Movie();
        Driven drivenClass = new Driven();
        drivenClass.fillArray();
        boolean kill = false;
        while (!kill) //!lose validation boolean?
        {
            System.out.printf("Customer or Employee? %n1: Customer %n2: Employee %nQ: Quit %n");

            switch (stdin.next())       //switch to determine if user is customer or employee.
            {
                case "1": //Customer
                    //copy and edit employee menu
                    break;
                case "2": //Employee
                    System.out.println("Enter password to continue or anything else to go back.");
                    while (stdin.next().equals("123456"))
                    {
                        boolean quit = false;
                        while (!quit)       //loop to allow sequential actions
                        {
                            System.out.printf("What would you like to do? %n1: Display %n2: Sort %n3: Search %n4: Add %n5: Remove %nQ: Quit %n");
                            switch (stdin.next())
                            {
                                case "1": //display
                                    drivenClass.displayMovies();
                                    //add display by type
                                    break;
                                case "2": //sort
                                    drivenClass.sortMovies();
                                    break;
                                case "3": //search
                                    drivenClass.searchMovies();
                                    break;
                                case "4": //add
                                    drivenClass.addMovies();
                                    break;
                                case "5": //remove
                                    drivenClass.removeMovies();
                                    break;
                                case "q":
                                    quit = true;
                                    break;
                                case "Q":
                                    quit = true;
                                    break;
                                default:
                                    System.out.println("Must be a number 1-5");
//                                    stdin.next();
                            }
                        }
                    }
                    break;
                case "q": //quit
                    kill = true;
                    break;
                case "Q": //quit
                    kill = true;
                    break;
                default:
                    System.out.println("Must enter a 1, 2, or Q.");
                    stdin.next();
            }
        }
    }
}


驱动类(有一些我在试图弄清楚时使用的东西被注释掉了,所以忽略它)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Driven {
    Scanner stdin = new Scanner(System.in);
    public ArrayList<Movie> movieList = new ArrayList<>();
    public void fillArray()     //method to populate ArrayList initially
    {
        movieList.add(new Movie("Kill All Humans", "Sci-fi", "Robot Assassin", 2138));
        movieList.add(new Movie("42", "Sci-fi", "Life, the universe, and everything", 5462));
        movieList.add(new Movie("Bloody Billy 17 -Yet Another Bloodfest", "Action", "B. J. Blackowitz", 1990));
        movieList.add(new Movie("Always Watching", "Documentary", "Big Brother", 1984));
        movieList.add(new Movie("Robot Samurai", "Kids", "Deus Ex Machina", 2012));
        movieList.add(new Movie("Giant Nuclear Frogs from the South", "Suspense", "Chuck Norris", 1998));
        movieList.add(new Movie("How to Make Cyanide from Apple Seeds", "Educational", "Adolf Hitler", 1940));
        movieList.add(new Movie("Two Birds with No Stones", "Martial-Arts", "Bruce Lee, Tim Cook, Edward Snowden", 1969));
        movieList.add(new Movie("Slow Internet!!!", "Suspense", "Sarah Connar, Linus Torvalds", 2004));
        movieList.add(new Movie("I Know Kung Fu", "Romance", "Steven Seagal, Jackie Chan", 2007));
        movieList.add(new Movie("Space Voyage", "Sci-fi", "Kirk, Spock", 1967));
        movieList.add(new Movie("Pointless Slaughter", "Thriller", "Stephen Hawking, Mike Tyson", 1999));
        movieList.add(new Movie("50 Shades of Death 2: Death before Diplomacy", "Thriller", "Donald Trump, Barrack Obama, Lots of Guns", 2023));
        movieList.add(new Movie("MTV (Music Television) - The Movie", "Action", "Bob Ross", 2010));
        movieList.add(new Movie("Spinach Sailor", "Documentary", "Popeye, Einstein", 1949));
        movieList.add(new Movie("Applegeddon - End of Humanity", "Documentary", "Steve Jobs, Steve Wozniak", 2099));
    }
    public void addMovies()     //method to add movies to full list
    { //!when adding 2 in a row it automatically puts a empty name
        System.out.println("Input movie name:");
        String names = stdin.nextLine();
        System.out.println("Input movie genre:");
        String genre = stdin.nextLine();
        System.out.println("Input movie actors/actresses:");
        String actor = stdin.nextLine();
        System.out.println("Input movie year:");
        while (!stdin.hasNextInt())
        {
            System.out.println("Must be a whole number");
            stdin.next();
        }
        int year = stdin.nextInt();
        movieList.add(new Movie(names, genre, actor, year));
        System.out.println("Movie added.");
    }
    public void removeMovies()      //method to delete movies from full list
    { //! add way to quit if chosen by accident
        System.out.println("Enter name of movie to remove.");
        String search = stdin.nextLine();
        for (int i = 0; i < movieList.size(); i++)
        {
            if (movieList.get(i).getName().equalsIgnoreCase(search))
            {
                System.out.printf("Remove this movie Y/N. %nName: %s %nGenre: %s %nActor: %s %nYear: %s %n %n", movieList.get(i).getName(), movieList.get(i).getGenre(), movieList.get(i).getActor(), movieList.get(i).getYear());
                if (stdin.next().equalsIgnoreCase("y"))
                {
                    movieList.remove(i);
                    System.out.println("Movie removed.");
                }
            }
        }
    }
    public void displayMovies()     //method to output the full list
    {
        for (Movie movie : movieList)
        {
            System.out.printf("Name: %s %nGenre: %s %nActor: %s %nYear: %s %n %n", movie.getName(), movie.getGenre(), movie.getActor(), movie.getYear());
        }
    }
    public void sortMovies()
    {
        System.out.printf("Sort by: %n1: Title %n2: Genre %n3: Actor/actress %n4: Year %n");
        boolean validChoice = false;
        while (!validChoice)
        {
            switch (stdin.next())
            {
                case "1": //sort by title
                    System.out.println("Enter sort method. 1 for bubble sort. 2 for selection sort.");
//                    displayMovies();
                    bubbleSort(movieList);
//                    Collections.sort(movieList, new Comparator<Movie>() {
//                        @Override
//                        public int compare(Movie o1, Movie o2) {
//                            return 0;
//                        }
//                    });
//                  movieList.get().getName().sort();
//                  movieList.sort(Collections.reverseOrder());
//                  System.out.println("sorted");
//                  displayMovies();
//                  movieList.sort(movieList.get(i).getName());
//                  Collections.sort(movieList.get().getName());
                    validChoice = true;
                    break;
                case "2": //sort by genre
                    System.out.println("Enter sort method. 1 for bubble sort. 2 for selection sort.");
                    validChoice = true;
                    break;
                case "3": //sort by actor
                    System.out.println("Enter sort method. 1 for bubble sort. 2 for selection sort.");
                    validChoice = true;
                    break;
                case "4": //sort by year
                    System.out.println("Enter sort method. 1 for bubble sort. 2 for selection sort.");
                    validChoice = true;
                    break;
                default:
                    validChoice = false;
                    System.out.println("Must enter 1-4");
                    stdin.next();
            }
        }
    }

    public void searchMovies()      //method to search for specific movie name
    { //!make it so spacing doesnt matter
        System.out.println("Enter name of movie to find.");
        String search = stdin.nextLine().toLowerCase();
        for (int i = 0; i < movieList.size(); i++) {
            if (movieList.get(i).getName().matches(search)) {
                System.out.printf("%s.%nName: %s %nGenre: %s %nActor: %s %nYear: %s %n %n", i+1, movieList.get(i).getName(), movieList.get(i).getGenre(), movieList.get(i).getActor(), movieList.get(i).getYear());
            }
        }
    }
//    public ArrayList setmovieList()
//    {
//        this.movieList = movieList;
//    }
    public ArrayList getmovieList()
    {
        return movieList;
    }
    private ArrayList bubbleSort()
    {
        getmovieList();
        Movie temp;
        for (int i = 0; i < movieList.size(); i++)
        {
            for (int j = 1; j < (movieList.get() - i); j++)
            {
                Movie jMovie = movieList.get(j).getMovie();
//                String compareLists = movieList.get(i-1).getName().toLowerCase();
//                System.out.println(compareLists);
                if (movieList.get(i).(movieList.get(i - 1).getName()) < 0)
//                    if (movieList.get(i).getName().toLowerCase().matches(compareLists))
                    {
                        System.out.println("Movie found ");
                        temp = movieList.get(i);
                        movieList.set(i, movieList.get(i-1));
                        movieList.set(i-1, temp);
                    }

            }
        }
    }
//    public ArrayList<Movie> getmovieList()       //!Lose?
//    {
//        return movieList;
//    }

}

//// Java program to demonstrate working of Collections.sort()
//import java.util.*;
//
//public class Collectionsorting
//{
//    public static void main(String[] args)
//    {
//        // Create a list of strings
//        ArrayList<String> al = new ArrayList<String>();
//        al.add("Geeks For Geeks");
//        al.add("Friends");
//        al.add("Dear");
//        al.add("Is");
//        al.add("Superb");
//
//      /* Collections.sort method is sorting the
//      elements of ArrayList in ascending order. */
//        Collections.sort(al);
//
//        // Let us print the sorted list
//        System.out.println("List after the use of" +
//                " Collection.sort() :\n" + al);
//    }
//}

电影课

import java.util.ArrayList;

public class Movie {
    private String name;
    private String genre;
    private String actor;
    private int year;


    public  Movie(String name, String genre, String actor, int year){
        this.name = name;
        this.genre = genre;
        this.actor = actor;
        this.year = year;
    }   //movie constructor

//    public Movie() { }

    public int getYear()
    {
        return year;
    }
    public String getActor()
    {
        return actor;
    }
    public String getGenre()
    {
        return genre;
    }
    public String getName()
    {
        return name;
    }
    public Movie getMovie(int i)
    {
        Movie temp = Driven.(getName(), getGenre().indexOf(i), getActor(i), getYear(i));
        return Movie();
    }
}

标签: javaarraylistbubble-sort

解决方案


我会给你一些提示。冒泡排序应该只需要从索引 1 开始的列表遍历一次。将其与下面的索引进行比较。如果 compareTo 返回 < 0,则将项目留在原处。否则交换这两个项目,然后再次将其与左侧的项目进行比较。因此,第二个 for 循环应该向索引 0 倒计时,并且当 compareTo 返回 >= 0 时,您应该中断该循环。

您在这条线上很接近,但您正在比较 i - 1 的字符串版本,而不是列表中 i - 1 处的字符串。

if (this.movieList.get(i).getName().compareToIgnoreCase(movieList.get(i - 1).getName()) < 0)

推荐阅读