对象的arraylist,无法静态引用非静态字段

时间:2019-03-07 09:23:05

标签: java

我正在尝试使用Java制作图书馆借阅系统

尝试对函数内部的arraylist使用循环我得到错误

  

无法静态引用非静态字段b

     

无法从类型库中静态引用非静态方法借书(String)

当我将所有内容放入评论之类的主要内容中

这是Book类代码

package  Book;


public class Book {



        /********************************/

        public String author;
        public String title;
        public int numcopies;
        public Book() {};
        public Book(String author, String title, int  
                 numcopies)         {

                    this.author = author;
                    this.title = title;
                    this.numcopies = numcopies;


            }
        /*********************************/


      /***********************************/
    public void setAuthor(String auth)
    {
        author = auth;
    }
    public void setTitle(String t)
    {
        title = t;
    }
    public void setNum(int n){
        numcopies = n;
    }   
      /********************************/
    public String getAuthor()
    {
        return author;
    }
    public String getTitle()
    {
        return title;
    }
    public int getNum(){
        return numcopies;
    }

      /********************************/


    public String Display()
    {
        return "\nAuthor: " +author + "\nTitle: " +title + 
      "\nNumber Of Copies " +numcopies +"\n ";
    }
}

这是包含方法的库代码

package Book;
import java.util.ArrayList;
public class Library {
    public ArrayList<Book> b = new ArrayList<>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*
          ArrayList<Book> b = new ArrayList<>();
        Book a = new Book("author","title",5);
        b.add(a);
        Book x = new Book("author1","title1",6);
        b.add(x);
        */
        /*
        for (Book BIteration:b ) {
            System.out.println(BIteration.Display()); 
        }

        */
        Book x = new Book("title","author",6);
        b.add(x);
        borrowBook("author");

    }
    public void addBook(Book book)
    {
        b.add(book);
    }

    public void borrowBook(String title) 
    {   
       int found = 0;
       for (Book c:b ) 
       {
           if (c.getTitle().equals(title)) 
           {
               if(c.getNum() != 0 ) {
                   found = 1 ; 
                   int m = c.getNum();
                   m--;
                   System.out.println("Good News, You can borrow this book.");

               }
               else {
                   System.out.println("Sorry, this book is already borrowed.");
               }

           }

       }
       if (found == 0) {
           System.out.println("Cannot Find this book.");
       }
       }
}

0 个答案:

没有答案