有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在创建用于ArrayList的气泡排序方法时遇到问题

试图为我的Java1类创建一个电影管理器时,我很难弄清楚如何使气泡排序方法与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;
                }

        }
    }
}

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

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

电影经理班

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) 个答案

  1. # 1 楼答案

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

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

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