开发者

Adding and retrieving elements from arrays of objects in java

Am creating a simple movie database with two classes namely Movie and Library.Library class has a a method addMovie which adds movie objects to an array of Movie objects. Another method borrowMovie retrieves movies from the movie object array and returnMovie returns Movie objects back in the array.It indicates that a movie has been returned, borrowMovie is supposed to work in a way that you cant borrow a movie twice unless it has been returned such that if someone tried to borrow it. it would show that its already borrowed and if its not in the Movie array it should indicate that the movie is not in the catalog. Another method printAvailableMovies should print all the movies in the library.Here is my sample code for movie and Library classes.

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

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

The main method for Library.java should output

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.

Now Movie.Java works perfectly and needs no modification but Library.java is a major source of pain because i can only make it work upto printing the library addresses. The methods borrowMovie,addMovie,returnMovie and printAvailableMovies are the culprits because they involve manipulating arrays of Movie Objects. The main method should not change and output should be as above when you test Library.java.Please change the code if you have to for these methods because my ideas dont seem to work. Any help would be appreciated.


I made some modifications - basically I removed unnecessary code from Movie, changed the library to be based on a Map as you only have one copy of each title - this will make searches faster. I added some 'error handling' - but I assume you can remove them and replace the exceptions with System.err.println for this piece of code.

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

Library.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();

    }
}

If you care about the order of the movies - use an ArrayList or LinkedList instead of the HashMap (And change the movieLibray member from Map to List)


If you need to be adding and removing things, it is best you use a List instead of an array. It will make your life a lot easier.

Basic List Example:

List<String> ls = new ArrayList<String>();
ls.add("one");
ls.add("Three");
ls.add("two");
ls.add("four");

for(String value : ls) {
  System.out.println("Value :"+value);
}

ls.remove("two");

for(String value : ls) {
  System.out.println("Value :"+value);
}

Issues I saw on the first pass:

addMovie() never increments i, so you are never writing to anything besides the first index of the array. This method is also extremely unsafe because it would be very easier to passing in a list of movies that is longer than the array you created. This returns me to my first point.

You are using instance variable for if a method was borrowed or returned, but you it is possible to borrow just one movie.


Try Now :

public class Library {

    String address;
    boolean borrowMovie,returnMovie;
    Movie[] libMovies =new Movie[5] ;
    int count = 0;

    public Library(String libraryAddress){
           address = libraryAddress;
    }

    public void addMovie(Movie... movies ){
       for( Movie item: movies){
       libMovies[count++] = item;}
    }

    public void borrowMovie(String movieTitle) {
        for (Movie item : libMovies) {
            if (movieTitle.equals(item.title)) {
                borrowMovie = true;
                break;
            }

        }

        if(!borrowMovie) {
            System.out.println("Sorry, this movie is not in our catalog.");
            return;
        }


        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++){
           if(libMovies[i] != null)
               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();

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜