2015-12-08 2 views
0

Я недавно начал программировать и столкнулся с несколькими незначительными ошибками. Я создаю объект библиотеки, который содержит ссылки на объекты книги и объекты-члены, однако мне не удается получить доступ к методам из класса-члена и использовать их в классе библиотеки без ошибок, возникающих в классе LibraryTester. Это то, что я закодированСоздание библиотеки с книжными объектами и объектами-объектами

класс Библиотеки

package assignment; 

import java.nio.channels.MembershipKey; 
import java.util.ArrayList; 
import java.util.Scanner; 

import org.omg.Messaging.SyncScopeHelper; 

public class Library { 

    // Declared an array list of type book 
    private ArrayList<Book> Books; 
    private MemberList members;; 
    public Library(ArrayList<Book> Books, Member member) { 
     this.Books = Books; 
     this.members=members; 
    }; 

    public void displayBooks() { 
     System.out.println("\t\t\t-----The Current Books in the library are-----"); 
     for (int i = 0; i < Books.size(); i++) { 
      System.out.println("\n" + "\t\t" + Books.get(i).getTitle() + "\t\t\t" + "\n\t\tAuthor: " 
        + Books.get(i).getAuthor() + "\n\t\tThis Books ID is: " + Books.get(i).getBookID() + "\t\t\t\t\t\t" 
        + "\n\t\tIs this book on loan? " + Books.get(i).getOnLoan() + "\t\t\t\t\t" 
        + "\n\t\tThe number of times which this book has been loaned: " + Books.get(i).getNumOfLoans() 
        + "\t\t"); 
     } 
    } 

    // method to remove permanently a book object 
    public void removeBook() // the parameter that is passed through 
           // is the book id of the book that is to 
           // be removed 

    { 
     Scanner input = new Scanner(System.in); 
     int bookID = 0; 

     boolean successful = false; 
     try { 
      do { 

       System.out.println("Please enter the book ID of the book you wish to delete"); 
       bookID = input.nextInt(); 
       for (int i = 0; i < Books.size(); i++) { 
        if (bookID == Books.get(i).getBookID()) 

        { 
         System.out.println("The Book " + Books.get(i).getTitle() + " was removed"); 
         Books.remove(i); 
         successful = true; 
         break; 

        } 

       } 
       if (!successful) { 
        System.out.println("Book ID " + bookID + " does not exist"); 
       } 

      } while (successful == false); 
     } catch (Exception e) { 
      System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu"); 
     } 
    } 

    public void editBook() { 

     boolean successful = false; 
     try { 
      do { 
       Scanner sc = new Scanner(System.in); 
       System.out.println("Please enter the book ID of the book who's details you wish to change"); 
       int bookID = sc.nextInt(); 
       sc.nextLine(); 
       for (int i = 0; i < Books.size(); i++) { 
        if (Books.get(i).getBookID() == bookID) { 

         System.out.println("Please enter the new name of the book:"); 
         String newTitle = sc.nextLine(); 
         Books.get(i).setTitle(newTitle); 
         System.out.println("Please enter the name of the author of the book:"); 
         String newAuthor = sc.nextLine(); 
         Books.get(i).setAuthor(newAuthor); 
         System.out.println("Change of book details successful" + "\nNew book title: " + newTitle 
           + "\nNew author: " + newAuthor); 
         successful = true; 
        } 

       } 

       if (!successful) { 
        System.out.println("This book does not exist "); 
       } 

      } while (successful == false); 
     } catch (Exception e) { 
      System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu"); 
     } 
    } 

    public void addBook() { 

     boolean successful = false; 
     int bookID = 0; 
     String title = ""; 
     String author = ""; 
     Scanner input = new Scanner(System.in); 

     do { 

      System.out.println("Please assign a 3 digit number for the books ID "); 
      bookID = input.nextInt(); 
      input.nextLine(); 
      if(bookID > 99 && bookID <1000){ 
      for (int i = 0; i < Books.size(); i++) { 
       if(Books.get(i).getBookID()!= bookID){ 
        successful = true; 
       } else { 
        System.out.println("This book ID already exists "); 
       } 
      } 
      } else { System.out.println("You must enter a number between 99 and 1000 "); 
      } 
     } while (successful == false); 

     do { 
      System.out.println("Please enter the name of book"); 
      title = input.nextLine(); 

      for (int i = 0; i < Books.size(); i++) { 
       if (Books.get(i).getTitle().equalsIgnoreCase(title)) { 
        System.out.println("ERROR: This book already exists"); 
        successful = false; 
       } else { 
        successful = true; 
       } 
      } 
     } while (successful == false); 

     do { 
      System.out.println("Please enter the author of the book"); 
      author = input.nextLine(); 

      successful = true; 

     } while (successful == false); 
     Book Book = new Book(bookID, title, author, false, 0, 0); 
     Books.add(Book); 
     System.out.println(
       "Book creation succcessful:" + "\nTitle: " + title + "\nAuthor: " + author + "\nBook ID:" + bookID); 
    } 

    public void loanBook() { 
     Scanner input = new Scanner(System.in); 
     boolean successful = false; 
     do { 

      System.out.println(
        "\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)"); 
      int bookID = input.nextInt(); 
      if (bookID == 9) { 
       successful = true; 
       break; 
      } 

      for (int i = 0; i < Books.size(); i++) { 
       if (Books.get(i).getBookID() == bookID) { 
        do { 
         System.out.println("\nHow long would you like to loan the book for (20 Days maximum):"); 
         int durationOnLoan = input.nextInt(); 
         if (durationOnLoan <= 20 && 1 <= durationOnLoan) { 
          Books.get(i).setDurationOnLoan(durationOnLoan); 
          successful = true; 
         } else { 
          System.out.println("The number of days you have entered is invalid"); 
         } 
        } while (successful == false); 

        System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan"); 
        Books.get(i).setOnLoan(true); 

        Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1); 
        successful = true; 
       } 

      } 

      if (successful == false) { 

       System.out.println("This book does not exist "); 
      } 

     } while (successful == false); 
    } 

    public void returnBook() { 

     boolean successful = false; 
     Scanner input = new Scanner(System.in); 
     try { 
      do { 

       System.out.println(
         "Please enter the book ID of the book you wish to return (Press 9 to exit to the main menu"); 
       int bookID = input.nextInt(); 
       input.nextLine(); 
       if (bookID == 9) { 
        successful = true; 
       } 

       for (int i = 0; i < Books.size(); i++) { 
        if (Books.get(i).getBookID() == bookID) { 
         if (Books.get(i).getOnLoan() == true) { 
          System.out.println("How long did you loan the book for?"); 
          int durationOnLoan = input.nextInt(); 
          if (durationOnLoan > Books.get(i).getDurationOnLoan()) { 
           durationOnLoan -= Books.get(i).getDurationOnLoan(); 
           if (durationOnLoan < 3) { 

            System.out.println("You are " + durationOnLoan 
              + " day(s) late in returning the book" + "\nYou have been fined £3." 
              + "\n The book " + Books.get(i).getTitle() + " is now returned"); 
            successful = true; 

           } else { 

            System.out.println("You are " + durationOnLoan + " days late in returning the book" 
              + "\nYou have been fined £6."); 
            System.out 
              .println("The book " + Books.get(i).getTitle() + " has now been returned"); 
            successful = true; 

           } 
          } else { 
           Books.get(i).setOnLoan(false); 
           System.out.println("The book " + Books.get(i).getTitle() + " has now been returned"); 
           successful = true; 
          } 

         } else if (Books.get(i).getOnLoan() == false) { 
          System.out.println("\nThis book was not on loan"); 
          System.out.println("\nYou have been returned to the main menu"); 
          successful = true; 
         } 
        } else if (successful == false) { 
         System.out.println("This book does not exist"); 
        } 
       } 

      } while (successful == false); 
     } catch (Exception e) { 
      System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu"); 

     } 
    } 

} 

класс

Пользователей
package assignment; 

import java.util.Scanner; 
import java.util.ArrayList; 

public class MemberList { 

    private ArrayList<Member> Members; 

    public MemberList(ArrayList<Member> Members) { 
     this.Members = Members; 
    } 

    public void addNewMember() { 

     Scanner input = new Scanner(System.in); 
     boolean successful = false; 
     int memberID = 0; 
     String memberName = ""; 
     int memberAge; 
     String address; 
     int contactNumber; 

     System.out.println("\t\tCreate new member"); 
     do { 


      System.out.println("Please enter your full name:"); 
      memberName = input.nextLine(); 
      if (!input.hasNextInt()) { 
       successful =true; 
      } else { 
       input.next(); 
       System.out.println("Your name cannot contain a number"); 
      } 


     } while (successful == false); 

     do { 
      try{ 
      input.nextLine(); 
      System.out.println("please create your unique 2 digit member ID"); 
      memberID = input.nextInt(); 
      for (int i = 0; i < Members.size(); i++) { 
       if (Members.get(i).getMemberID() == memberID) { 
        System.out.println("This member ID is already in use"); 
        successful =false; 
       } 
       if (memberID <= 9 || memberID > 99) { 
        System.out.println("PLease enter 2 digit ID (between 10 and 100) "); 
       } 
       if(Members.get(i).getMemberID() != memberID && memberID > 9 && memberID < 100) { 
        successful = true; 
       } 
      } 

      } catch(NumberFormatException e) 
      { 
       System.out.println("Invalid input"); 
      } 
     } while (successful == false); 

     do{ 
      System.out.println("Please enter your age: "); 
      memberAge = input.nextInt(); 
      if(!input.hasNextInt()) 
      { 
       System.out.println("Invalid input"); 
      } else{successful =true;} 

     }while(successful == false); 

     do{ 

      System.out.println("Please enter your adress"); 
      address = input.nextLine(); 
      successful =true; 
     }while(successful==false); 

     do { 
      System.out.println("please enter your contact number:"); 
      contactNumber = input.nextInt(); 
      if(!input.hasNextInt()) 
      { 
       System.out.println("Invalid input"); 
      } else{successful = true;} 

     }while(successful==false); 

     Member newMember = new Member(memberID,memberName,memberAge,0,0,address,contactNumber); 
     Members.add(newMember); 


    } 

    public void displayMembers() 
    { 
     System.out.println("\t\t\t-----The current members in the library are-----"); 
     for (int i = 0; i < Members.size(); i++) 
     { 
         System.out.println("\n" + "\t\t" + Members.get(i).getMemberName() + "\t\t\t" + "\n\t\tMember ID: " 
        + Members.get(i).getMemberID() + "\n\t\tAge: " + Members.get(i).getMemberAge() + "\t\t\t\t\t\t" 
        + "\n\t\tAddress: " + Members.get(i).getAddress() + "\t\t\t\t\t" 
        + "\n\t\tContact number: " + Members.get(i).getContactNumber() 
        + "\t\t" + "\n\t\tNumber of books loaned: " + Members.get(i).getNumOfBooksLoaned() 
        + "\t\t" + "\n\t\tNumber of Late Fees: " + Members.get(i).getPenalties()); 
     } 
    } 
} 

LibraryTester Класс

package assignment; 

import java.util.Scanner; 
import java.util.ArrayList; 

public class LibraryTester { 

    public static void main(String[] args) { 

     String title = ""; 
     String author = ""; 
     int bookID = 0; 


     ArrayList<Member> List = new ArrayList<Member>(); 
     MemberList memberlist = new MemberList(List){}; 

     Member John = new Member(10,"John McLaughlin", 44, 5, 0,"75 B Loughbeg Road Toomebridge",123456789); 
     List.add(John); 
     Member Cathy = new Member(11,"Cathy McLaughlin", 43, 7, 0,"75 B Loughbeg Road Toomebridge",123456789); 
     List.add(Cathy); 


     ArrayList<Book> list = new ArrayList<Book>(); 
     Library library = new Library(list,); 


     Book HarryPotter = new Book(100, "Harry Potter and The Philosopher's Stone", "J.K Rowling", false, 5, 0); 
     list.add(HarryPotter); 
     Book theOriginOfSpecies = new Book(101, "The Origin Of Species", "Charles Darwin", false, 3, 0); 
     list.add(theOriginOfSpecies); 
     Book LOTR = new Book(102, "The Lord of The Rings: The Fellowship of The Ring", "J.R.R Tolkien", false,7,0); 
     list.add(LOTR); 

     Scanner input = new Scanner(System.in); 


     boolean B = true; 

     while (B == true) { 

      System.out.println(" \nMenu "); 
      System.out.println("Press 1 to add a book"); 
      System.out.println("Press 2 to edit a books details"); 
      System.out.println("Press 3 to delete a book"); 
      System.out.println("Press 4 to take out a book on loan"); 
      System.out.println("Press 5 to return a book"); 
      System.out.println("Press 6 to see all the books in the library"); 
      System.out.println("Press 7 to become a member"); 
      System.out.println("Press 8 to see the members of the library"); 
      System.out.println("Press 9 to exit the program"); 

      switch (input.nextInt()) { 

      case 1: 

       library.addBook(); 
       B = true; 
       break; 

      case 2: 
       library.displayBooks(); 
       library.editBook(); 
       B = true; 
       break; 

      case 3: 

       library.displayBooks(); 
       library.removeBook(); 

       B = true; 
       break; 

      case 4: 
       library.displayBooks(); 
       library.loanBook(); 

       B = true; 
       break; 

      case 5: 
       library.displayBooks(); 
       library.returnBook(); 
       break; 
      case 6: 

       library.displayBooks(); 
       B = true; 
       break; 
      case 7: 
       memberlist.addNewMember(); 
       break; 
      case 8: 
       memberlist.displayMembers(); 
       B = true; 
       break; 
      case 9: 
       System.out.println("Exiting ....."); 
       System.exit(1); 
       break; 
      default: 
       System.out.println("You have not entered a valid option"); 
       break; 

      } 

     } 
    } 

} 

Ошибка возникает в коде

Library library = new Library(list ,) { 
}; 

Я не уверен, что положить после запятой, я пробовал все, и ничего не работает. Есть предположения?

EDIT

класса

Edited Библиотека

package assignment; 

import java.nio.channels.MembershipKey; 
import java.util.ArrayList; 
import java.util.Scanner; 

import org.omg.Messaging.SyncScopeHelper; 

public class Library { 

    // Declared an array list of type book 
    private ArrayList<Book> Books; 
    private ArrayList<Member> members;; 
    public Library(ArrayList<Book> Books, ArrayList<Member> member) { 
     this.Books = Books; 
     this.members=member; 
    }; 

Edited LibraryTester класс

ArrayList<Member> List = new ArrayList<Member>(); 
MemberList memberList = new MemberList(List){}; 


ArrayList<Book> list = new ArrayList<Book>(); 
Library library = new Library(list, memberList){}; 

Ошибка говорит "Конструктор библиотека (ArrayList, участники) не определена" Но я изменил соответствующие вещи в классе библиотеки?

+1

Какие ошибки вы видите? Опубликуйте полные сообщения об ошибках, поскольку они содержат много полезной информации и часто сообщают вам, что именно не так. –

+0

Ваш конструктор библиотеки ожидает список книг и член: 'Библиотека библиотеки = новая библиотека (список, новый член();' – Cir0X

+0

Почему вы импортируете (и не используете) 'java.nio.channels.MembershipKey' и' org.omg.Messaging.SyncScopeHelper'? Также очень важно: переменные и поля начинаются с буквы * в нижнем регистре, используйте 'ArrayList members' и' ArrayList books' вместо того, что вы делаете сейчас. –

ответ

0

Вам нужно передать массив книги и член:

public Library(ArrayList<Book> Books, Member member) 
0

Так как библиотека класса, имеющий конструктору

public Library(ArrayList<Book> Books, Member member){}; 

вы не можете просто создать объект, как вы делаете в классе LibraryTester. вам нужно передать второй параметр i.e, объект класса Member.

0

Здесь вы пропустите член:

Library library = new Library(list,); 

Try, чтобы добавить его, как это создание объекта члена:

Member memberlist = new Member(10,"Joe Blogs", 44, 5, 0,"Bleaker Street",123456789); 
    Library library = new Library(list, memberlist); 
+0

Я пробовал библиотеку библиотеки = новая библиотека (список, список участников); 'и она не работает. –

+0

однако 'Библиотека библиотеки = новая библиотека (список, новый участник (10,« Joe Blogs », 44, 5, 0,« Bleaker Street », 123456789)) {};' works –

+0

@ C.Darwin попытаться взглянуть наверху я думаю, что это то же самое, прежде чем вы должны быть уверены, что memberlist является экземпляром Member. – Abdelhak

Смежные вопросы