无法创建与ArrayList一起使用的冒泡排序方法

时间:2019-05-08 17:01:57

标签: java arraylist bubble-sort

试图为我的java 1类创建一个电影管理器,但是我很难弄清楚如何使冒泡排序方法与arraylist一起使用。 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;
                }

        }
    }
}

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

*编辑 这是我到目前为止的全部代码

MovieManager类

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();
    }
}

1 个答案:

答案 0 :(得分:0)

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

您已经接近这一行,但是您正在与i-1的字符串版本进行比较,而不是与i-1列表中的字符串进行比较。

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