【问题标题】:Difficulty setting and updating objects in a Sorted ArrayList [duplicate]难以在排序的 ArrayList 中设置和更新对象 [重复]
【发布时间】:2021-03-24 09:52:21
【问题描述】:

我希望能够更新有关用户输入的对象的信息。我希望用户输入书名和用户名以取出书,并且能够以相同的信息返回它。对象必须插入到我的 sortedarraylists 中的正确位置。假设每个用户都是唯一的,每本书只能由一个用户取出(最多可以取出 3 本书)。

当我尝试编译我的代码时,我收到以下错误消息:

java: method issueBook in class Driver cannot be applied to given types;
  required: Book,User
  found:    no arguments
  reason: actual and formal argument lists differ in length

这对应于 issueBook();以防我的菜单。

我还有实现Comparable<Book> 等的User 和Book 类。我尽量省略不相关的代码,例如文件阅读器扫描新用户和书籍对象。我包括了书籍和用户类,以防需要查看(我认为它们大多都很好)。如果您需要更多详细信息,请告诉我。

import java.io.*;
import java.util.Scanner;

public class Driver {

    static Scanner sc = new Scanner(System.in);

    private static void mainMenu() {
        System.out.println("------------------------------\n"+
                "f: Finish running the program\n" +
                "b -Display on the screen the information about all the books in the library\n" +
                "u -Display on the screen the information about all the users.\n" +
                "i -Update the stored data when a book is issued to a user\n" +
                "r -Update the stored data when a user returns a book to the library\n" +
                "------------------------------\n" +
                "Type a letter and press Enter\n");
    }

 private static User readNames() throws User.InvalidBookLimitException {
        System.out.println("Enter the user's firstname: ");
        String firstName = sc.next();
        System.out.println("Enter the user's surname: ");
        String surName = sc.next();
        sc.nextLine();                                    //TODO check this
        return new User(firstName, surName, 0);
    }

    private static User readUserData(User user) throws User.InvalidBookLimitException {
        User u = readNames();
        System.out.println("Enter " + user + "'s age, and press Enter");
        int numberOfBooks = sc.nextInt();
        sc.nextLine();
        return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
    }

    private static Book readBookName (){
        System.out.println("Type in the name of the book");
        String bookName = sc.nextLine();
        return new Book(bookName);
    }

/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>();    public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/ 
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.

    public void issueBook(Book book, User user){
        for (Book b : sortedBooks){
            if(b.equals(book)){
                b.loanStatus(true);
                /*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
                break;
            }
        }
        for (User u: sortedUsers){
            if(u.equals(user)){
                u.setNumberOfBooks(u.getNumberOfBooks()+1);

            }
        }
    }

    public void returnBook(Book book, User user){
        for (Book b : sortedBooks){
            if(b.equals(book)){
                 b.loanStatus(false);
                 b.setLoanerNames(null, null);
                break;

            } for (User u: sortedUsers){
                if(u.equals(user)){
                    u.setNumberOfBooks(u.getNumberOfBooks()-1);
                }
            }
        }
    }

    public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
        //These SortedArrayLists have been derived from the sorted arraylist class
        SortedArrayList<User> sortedUsers = new SortedArrayList<>();
        SortedArrayList<Book> sortedBooks = new SortedArrayList<>();

mainMenu(); //main menu printing method
        char ch = sc.next().charAt(0);
        sc.nextLine();
        while (ch !='f') //the program ends as desired if f is pressed


        { switch(ch){

            case 'b':
                System.out.println("Displaying information about all books in the library: ");
                /*for (Object item : sortedBooks) {
                    System.out.println(sortedBooks.toString());
                }*/
                System.out.println(sortedBooks/*.toString()*/);

                break;
            case 'u':
                System.out.println("Displaying information about all users");
                System.out.println(sortedUsers/*.toString()*/);
                break;

            case 'i':
                System.out.println("Enter the loaning out data. ");
                System.out.println("Enter the user's first name and surname: ");
                readNames();
                System.out.println("Enter the name of the book: ");
                readBookName();
                issueBook();
              
                or maybe  if(u1.compareTo(u2) == 0)*/

                break;
            case 'r':
                System.out.println("Please the details of the book to be returned: ");
                /*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work 
                /*returnBook(b);*/

                break;

            default:
                System.out.println("Invalid input, please enter f, b, i or r");

        }
        mainMenu();
        ch = sc.next().charAt(0);
            sc.nextLine();
        }
    }
}

我的带有(工作)插入方法的排序数组列表类:

import java.util.ArrayList;

public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {

    //no need for a generic in the insert method as this has been declared in the class
    public void insert(E value) {
        if (this.size() == 0) {
            this.add(value);
            return; }
        for (int i = 0; i < this.size(); i++) {
            int comparison = value.compareTo((E) this.get(i));
            if (comparison < 0) {
                this.add(i, value);
                return; }
            if (comparison == 0) {
                return; }
        }

        this.add(value);
    }

用户类别:

import java.io.PrintWriter;

public class User implements Comparable<User> {
    private String firstName;
    private String surName;
    private int numberOfBooks;

    public User(){
        firstName = "";
        surName = "";
        numberOfBooks = 0;
    }

    public class InvalidBookLimitException extends Exception{
        public InvalidBookLimitException(){
            super("Invalid number of books");
        }

    }

    public User(String name1, String name2, int books) throws InvalidBookLimitException {

        this.firstName = name1;
        this.surName = name2;
        if (books>3) throw new InvalidBookLimitException ();
        this.numberOfBooks = books;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getSurName(){
        return surName;
    }

    public int getNumberOfBooks(){
        return numberOfBooks;
    }

    public boolean borrowMoreBooks(){
        return numberOfBooks < 3;
    }

    public void setNumberOfBooks(int numberOfBooks){
        this.numberOfBooks=numberOfBooks;
    }

    public void setUser(String name1, String name2, int books){
        firstName = name1;
        surName = name2;
        numberOfBooks = books;

    }


    public boolean userNameTest (User otherUser){
        return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
    }


  /*  public boolean loanAnotherBook(){
        return !(numberOfBooks<3);
        numberOfBooks++;
    }*/
    public void printName(PrintWriter f){f.println(firstName+ " " + surName);}


/*
    public void setUser(User user) {
        if (loanStatus == false){
            loanStatus = Driver.readNameInput();
            loanStatus = true;
        }
    }*/
    @Override
    public String toString(){
        return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
    }



    public int compareTo(User u) {
       /* int snCmp = surName.compareTo(u.surName);
        if (snCmp != 0)
            return snCmp;
        else{
            int fnCmp = firstName.compareTo(u.firstName);
            if (fnCmp !=0)
                return fnCmp;
        }*/

        int fnCmp = firstName.compareTo(u.firstName);
        if (fnCmp != 0) return fnCmp;
        int snCmp= surName.compareTo(u.surName);
        if (snCmp !=0) return snCmp;
        else return numberOfBooks -u.numberOfBooks;



    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}

书籍类:

public class Book implements Comparable<Book>{
    public String bookName;
    public String authorName;
    public boolean loanStatus;
    public String loanerFirstName;
    public String loanerSurName;
    //if boolean loanStatus == true private string loaner name

    public Book(){
        bookName = "";
        authorName = "";
        loanStatus = false;
        loanerFirstName = null;
        loanerSurName = null;
    }

    Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {

        this.bookName = book;
        this.authorName = author;
        this.loanStatus = loanStatus;
        this.loanerFirstName = loanerFirstName;
        this.loanerSurName = loanerSurName;
    }
    Book(String book){
        this.bookName=book;
    }



    public String getBookName(){
        return bookName;
    }
    public String getAuthorName(){
        return bookName;
    }
    public boolean getLoanStatus(){
        return loanStatus;
    }

    public String getLoanerFirstName(){
        return loanerFirstName;
    }
    public String getLoanerSurName(){
        return loanerSurName;
    }


    public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
        bookName = book;
        authorName = author;
        loanStatus = loanStatus;
        loanerFirstName = loanerFirstName;
        loanerSurName = loanerSurName;


    }

    public void setBookName(String bookName){
        this.bookName=bookName;
    }

    public void loanStatus(boolean loanStatus){
        this.loanStatus=loanStatus;
    }
    public void setLoanerNames(String loanerFirstName, String loanerSurName){
        this.loanerFirstName=loanerFirstName;
        this.loanerSurName=loanerSurName;
    }

 /*   public boolean nameTest (User otherUser){
        return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
    }
*/

    public String toString(){

        return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
    }


    //this may be redundant TODO
  /*  public void setLoanStatus(User user){
        loanStatus = false;

    }*/

    //This compare method allows new user objects to be compared to ones in the
 @Override       //sortedArrayList, enabling the insertion method.
    public int compareTo(Book b) {
        int bnCmp = bookName.compareTo(b.bookName);
        if (bnCmp != 0) return bnCmp;
        int anCmp= authorName.compareTo(b.authorName);
        if (anCmp !=0) return anCmp;
//        int lsCmp= loanStatus.(b.loanStatus);
//        if (lsCmp !=0) return lsCmp;
        int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
        if (lrfnCmp !=0) return lrfnCmp;
        int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
        if (lrlnCmp !=0) return lrlnCmp;
        else return 0;

    }
}

【问题讨论】:

  • 在 Driver 类 switch 语句中,对于案例 i,您正在调用方法 issueBook() 而不传递任何参数。但是issueBook 期望 Book 和 User 根据其定义 issueBook(Book book, User user) 作为参数。请传递适当的参数。希望这会有所帮助!
  • 嗨,谢谢你,但是在调用这些方法之前,我已经创建了 book 和 user 对象,所以我不明白为什么仍然会发生这种情况
  • 您已经创建了对象,但没有在 issueBook 方法中传递这些对象。

标签: java generics arraylist


【解决方案1】:
User user = readNames();
Book book = readBookName();
issueBook(book, user);

您必须在调用 issueBook 方法时传递您创建的用户和书籍。

【讨论】:

  • 您好,谢谢。我试过了,但得到了 186:17 java: non-static method issueBook(Book,User) cannot be referenced from a static context
  • 这可能会对您有所帮助:stackoverflow.com/questions/290884/…。您可以使您的 issueBook 静态类似于其他方法 readNames() 和 readBookName()
  • 您好,谢谢。我尝试将 issueBook 方法设为 public void static,但随后出现与数组列表 sortedBooks 和 sortedUsers 相对应的错误:无法从静态上下文中引用非静态字段“sortedBooks”。这似乎会产生一连串的问题。
  • 您可以将字段和方法设为静态以便您可以直接访问它们,或者您可以创建一个类的对象并使用该对象进行访问。这可能有助于您理解 stackoverflow.com/questions/2559527/… 的概念
猜你喜欢
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
相关资源
最近更新 更多