java - 在java中添加和检索对象数组中的元素

标签 java arrays

我正在创建一个简单的电影数据库,其中包含两个类,即 Movie 和 Library。Library 类有一个方法 addMovie,它将电影对象添加到 Movie 对象数组中。另一种方法borrowMovie从电影对象数组中检索电影,returnMovie将Movie对象返回到数组中。它表明电影已被返回,borrowMovie应该以这样的方式工作:你不能借电​​影两次,除非它已经被返回如果有人试图借用它。它会显示它已经被借用,如果它不在 Movie 数组中,它应该表明该电影不在目录中。 另一个方法 printAvailableMovies 应该打印库中的所有电影。这是我的电影和库类的示例代码。

电影.java

public class Movie {

    public String title;
    boolean borrowed,returned;

    // Creates a new Movie
    public Movie(String movieTitle) {
        
       title = movieTitle;
    }
   
    
    // Marks the movie as rented
    public void borrowed() {
        
        borrowed = true;
    }
   
    // Marks the movie as not rented
    public void returned() {
        
           returned = true;
    }
   
    // Returns true if the movie is rented, false otherwise
    public boolean isBorrowed() {
        
        if(borrowed && !returned)
          return true;
          else
          return false;
         
    }
   
    // Returns the title of the movie
    public String getTitle() {
       
        
      return title;
    }

    public static void main(String[] arguments) {
        // Small test of the Movie class
        Movie example = new Movie("Christmas in Kampala");
        System.out.println("Title (should be Christmas in Kampala): " + example.getTitle());
        System.out.println("Borrowed? (should be false): " + example.isBorrowed());
        example.borrowed();
        System.out.println("Borrowed? (should be true): " + example.isBorrowed());
        example.returned();
        System.out.println("Borrowed? (should be false): " + example.isBorrowed());
    }
} 

库.java

public class Library {
    
    String address;
    boolean borrowMovie,returnMovie;
    Movie[] libMovies =new Movie[5] ;
    
    public Library(String libraryAddress){
           address = libraryAddress;
    }
    
    public void addMovie(Movie... movies ){
       int i = 0;
       for( Movie item: movies){
       libMovies[i] = item;}
    }
    public void borrowMovie(String movieTitle){
        for(Movie item: libMovies){
        if(movieTitle.equals(item.title))
        borrowMovie = true;
         else
         System.out.println("Sorry, this movie is not in our catalog.");
         }
        if(borrowMovie&&!returnMovie)
        System.out.println("You have successfully borrowed " + movieTitle);
        else
        System.out.println("Sorry, this movie is already borrowed.");
        
    }*/
    public void returnMovie(String movieTitle){
           returnMovie = true;
           System.out.println("You successfully returned " + movieTitle);
           }
      
    public static void printOpeningHours(){
       System.out.println ("Libraries are open daily from 9am to 5pm.");
    }
    public void printAddress(){
          System.out.println( address);
    }
    public void printAvailableMovies(){
           
       for( int i =0;i < libMovies.length;i++){
       System.out.println(libMovies[i].getTitle());}
      // if(item == null)
       //System.out.println("No movie in catalog.");

    }
    public static void main(String[] args) {
        // Create two libraries
        Library firstLibrary = new Library("Plot 11, Kafene Road");
        Library secondLibrary = new Library("Plot 28, Kayembe Road");

        // Add four movies to the first library
        firstLibrary.addMovie(new Movie("Yogera"));
        firstLibrary.addMovie(new Movie("The Last King of Scotland"));
        firstLibrary.addMovie(new Movie("The Hostel"));
        firstLibrary.addMovie(new Movie("Christmas in Kampala"));

        // Print opening hours and the addresses
        System.out.println("Library hours:");
        printOpeningHours();
        System.out.println();
        
        System.out.println("Library addresses:");
        firstLibrary.printAddress();
        secondLibrary.printAddress();
        System.out.println();

        
        // Try to borrow Christmas in Kampala from both libraries
        System.out.println("Borrowing Christmas in Kampala:");
        firstLibrary.borrowMovie("Christmas in Kampala");
        firstLibrary.borrowMovie("Christmas in Kampala");
        secondLibrary.borrowMovie("Christmas in Kampala");
        System.out.println();

        Print the titles of all available movies from both libraries
        System.out.println("Movies available in the first library:");
        firstLibrary.printAvailableMovies();
        System.out.println();
        System.out.println("Movies available in the second library:");
        secondLibrary.printAvailableMovies();
        System.out.println();

        // Return Christmas in Kampala to the first library
        System.out.println("Returning Christmas in Kampala:");
        firstLibrary.returnMovie("Christmas in Kampala");
        System.out.println();

        // Print the titles of available movies from the first library
        System.out.println("Movies available in the first library:");
        firstLibrary.printAvailableMovies();
        
    }
} 

Library.java 的 main 方法应该输出

Library hours:

Libraries are open daily from 9am to 5pm.

Library addresses:

Plot 11, Kafene Road

Borrowing Christmas in Kampala:

You successfully borrowed Christmas in Kampala

Sorry, this movie is already borrowed.

Sorry, this movie is not in our catalog.

Movies available in the first library:

Yogera

The Last King of Scotland

The Hostel

Movies available in the second library:

No movie in catalog

Returning Christmas in Kampala:

You successfully returned Christmas in Kampala

Movies available in the first library:

Yogera

The Last King of Scotland

The Hostel

Christmas in Kampala.

现在 Movie.Java 工作完美,不需要修改,但 Library.java 是一个主要的痛苦来源,因为我只能让它工作到打印库地址。 borrowMovie、addMovie、returnMovie 和 printAvailableMovies 方法是罪魁祸首,因为它们涉及操作 Movie 对象数组。当您测试 Library.java 时,main 方法不应更改,输出应如上。如果必须对这些方法进行更改,请更改代码,因为我的想法似乎不起作用。任何帮助将不胜感激。

最佳答案

我做了一些修改 - 基本上我从 Movie 中删除了不必要的代码,将库更改为基于Map,因为每个标题只有一份副本 - 这将使搜索速度更快。我添加了一些“错误处理” - 但我假设您可以删除它们并用 System.err.println 替换这段代码的异常。

电影.java:

public class Movie
{
    public String title;
    boolean borrowed;

    // Creates a new Movie
    public Movie(String movieTitle)
    {
        title = movieTitle;
    }

    // Marks the movie as rented
    void borrow() throws Exception
    {
        if (this.borrowed)
        {
            throw new Exception("The movie <" + this.title + "> is already borrowed - cannot borrow it again");
        }
        else
        {
            this.borrowed = true;
        }
    }

    // Marks the movie as not rented
    void returnMovie() throws Exception
    {
        if (this.borrowed)
        {
            this.borrowed = false;
        }
        else
        {
            throw new Exception("The movie <" + this.title + "> has not been borrowed - it cannot be returned");
        }
    }

    // Returns true if the movie is rented, false otherwise
    public boolean isBorrowed()
    {
        return this.borrowed;
    }

    // Returns the title of the movie
    public String getTitle()
    {
        return title;
    }

    public static void main(String[] arguments) throws Exception
    {
        // Small test of the Movie class
        Movie example = new Movie("Christmas in Kampala");
        System.out.println("Title (should be Christmas in Kampala): " + example.getTitle());
        System.out.println("Borrowed? (should be false): " + example.isBorrowed());
        example.borrow();
        System.out.println("Borrowed? (should be true): " + example.isBorrowed());
        example.returnMovie();
        System.out.println("Borrowed? (should be false): " + example.isBorrowed());
    }
}

库.java:

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Library
{
    String address;
    Map<String, Movie> movieLibrary;

    public Library(String libraryAddress)
    {
        address = libraryAddress;
        this.movieLibrary = new HashMap<String, Movie>();
    }

    public void addMovie(Movie... movies)
    {
        for (Movie item : movies)
        {
            this.movieLibrary.put(item.getTitle(), item);
        }
    }

    public void borrowMovie(String movieTitle)
    {
        Movie movie = this.movieLibrary.get(movieTitle);

        if (movie == null) // Not in libray
        {
            System.out.println("Sorry, this movie is not in our catalog.");
        }
        else
        {
            if (movie.isBorrowed())
            {
                System.out.println("Sorry, this movie is already borrowed.");
            }
            else
            {
                try
                {
                    movie.borrow();
                    System.out.println("You have successfully borrowed " + movieTitle);
                }
                catch (Exception e)
                {
                    System.out.println("An internal error has occured while attempting to borrow " + movieTitle + ", error details: " + e.getMessage());
                }
            }
        }
    }

    public void returnMovie(String movieTitle)
    {
        Movie movie = this.movieLibrary.get(movieTitle);

        if (movie == null) // Not in libray
        {
            System.out.println("Sorry, this movie is not in our catalog.");
        }
        else
        {
            if (movie.isBorrowed())
            {
                try
                {
                    movie.returnMovie();
                    System.out.println("You successfully returned " + movieTitle);
                }
                catch (Exception e)
                {
                    System.out.println("An internal error has occured while attempting to return " + movieTitle + ", error details: " + e.getMessage());
                }
            }
            else
            {
                System.out.println("Sorry, this movie is has not been borrowed.");
            }
        }
    }

    public static void printOpeningHours()
    {
        System.out.println("Libraries are open daily from 9am to 5pm.");
    }

    public void printAddress()
    {
        System.out.println(address);
    }

    public void printAvailableMovies()
    {
        Collection<Movie> movies = this.movieLibrary.values();

        if (movies.size() > 0)
        {
            for (Movie movie : movies)
            {
                if (!movie.isBorrowed())
                {
                    System.out.println(movie.getTitle());
                }
            }
        }
        else
        {
            System.out.println("No movie in catalog.");
        }

    }

    public static void main(String[] args)
    {
        // Create two libraries
        Library firstLibrary = new Library("Plot 11, Kafene Road");
        Library secondLibrary = new Library("Plot 28, Kayembe Road");

        // Add four movies to the first library
        firstLibrary.addMovie(new Movie("Yogera"));
        firstLibrary.addMovie(new Movie("The Last King of Scotland"));
        firstLibrary.addMovie(new Movie("The Hostel"));
        firstLibrary.addMovie(new Movie("Christmas in Kampala"));

        // Print opening hours and the addresses
        System.out.println("Library hours:");
        printOpeningHours();
        System.out.println();

        System.out.println("Library addresses:");
        firstLibrary.printAddress();
        secondLibrary.printAddress();
        System.out.println();

        // Try to borrow Christmas in Kampala from both libraries
        System.out.println("Borrowing Christmas in Kampala:");
        firstLibrary.borrowMovie("Christmas in Kampala");
        firstLibrary.borrowMovie("Christmas in Kampala");
        secondLibrary.borrowMovie("Christmas in Kampala");
        System.out.println();

        // Print the titles of all available movies from both libraries
        System.out.println("Movies available in the first library:");
        firstLibrary.printAvailableMovies();
        System.out.println();
        System.out.println("Movies available in the second library:");
        secondLibrary.printAvailableMovies();
        System.out.println();

        // Return Christmas in Kampala to the first library
        System.out.println("Returning Christmas in Kampala:");
        firstLibrary.returnMovie("Christmas in Kampala");
        System.out.println();

        // Print the titles of available movies from the first library
        System.out.println("Movies available in the first library:");
        firstLibrary.printAvailableMovies();

    }
}

如果您关心电影的顺序 - 使用 ArrayListLinkedList 而不是 HashMap (并更改 movieLibray 成员从 MapList)

关于java - 在java中添加和检索对象数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556499/

相关文章:

java - 像耐心/克朗代克纸牌游戏一样拖动节点

python - 是否存在使用两个图像(二维数组)作为输入的图像的一维插值(沿一个轴)?

python - 比较列表理解和显式循环(3 个数组生成器比 1 个 for 循环更快)

javascript - 使用 .find 或 .find 内部的 .index

javascript - 从数组值中获取值以形成聊天

java - 重复写入数据库或文本文件

java - JPA OneToMany 关系未填充/填充/仍然为空

java - 如何在不下载的情况下获取S3上csv文件的行数?

java - 露天休息,文件上传: cannot set description and filename

php - 这是 PHP 数组访问的错误吗?