简体   繁体   中英

Java: How to count occurrences in an arraylist, then get it to print that output in a toString?

So I am making a library book simulation, the current part I am stuck on is trying to find the number of books on loan and to then for this to be printed out when the toString method is called.

public class Biblio{
    private ArrayList<Book> collection;
    private int loanCount;

The status of the book is of type enum

public enum Status {LOAN, REFERENCE, AVAILABLE};

the code I am stuck on:

public int numberOfBooksOnLoan(){
    int loanCount= 0;
    for(Book onLoan: collection){
        if(onLoan.getBookStatus()== Status.LOAN){
            loanCount++;    
        }
    }
    return loanCount;
}


      @Override
public String toString(){
    StringBuilder string= new StringBuilder();
    string.append("total number of books: ").append(bookCollection.size()).append("\n");
    string.append("number of loaned books: ").append(loanCount).append("\n");
    return string.toString();
}

both numberOfBooksOnLoan and the toString methods are in the Biblio class

When I use the toString method, the value 0 is printed, even when books are on loan, in contrast to the getLoanCount method (also in this class) which will print the required value.

My question is, how can I go through an arraylist and count all the books which are on loan then have this value stored in a variable so I can use it in the toString? Or more generally, how do you go through an arraylist and count all objects with a specific variable in common?

In case this is part of the problem, I have the warning 'local variable hides a field' in reference to

int loanCount = 0;

Do you have a instance variable also called loanCount? If the answer is yes try removing the instance one and change toString to call the method:

@Override
public String toString(){
    StringBuilder string= new StringBuilder();
    string.append("total number of books: ").append(bookCollection.size()).append("\n");
    string.append("number of loaned books: ").append(numberOfBooksOnLoan()).append("\n");
    return string.toString();
}
public int numberOfBooksOnLoan(){
 int loanCount= 0;
 for(Book onLoan: collection){
    if(onLoan.getBookStatus()== Status.LOAN){
        loanCount++;    
    }
 }
 return loanCount;
}

You are creating a local variable in numberOfBooksOnLoan() but in your toString() method your are using the class attribute loanCount .

Just remove int from int loanCount= 0; in the numberOfBooksOnLoan() so you will use the class attribute instead of the local variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM