Error for the java the last project,I don't understand how to compare the boolean value in hashmap


#1

import java.util.HashMap;
public class Library{
public Library(){
}
public void getFinishedBooks(HashMaplibrary){
if(library.size()<1){
System.out.println("Error");
}
else{
for(String book:library.keySet()){
if(book.getValue()==true){
System.out.println(book.getKey());
}
}
}
}

public static void main(String[] args){
HashMap myBooks=new HashMap();
myBooks.put("Road Down The Funnel", true);
myBooks.put("Rat: A Biology", false);
myBooks.put("TimeIn", true);
myBooks.put("3D Food Printing", false);
Library myLibrary=new Library();
myLibrary.getFinishedBooks(myBooks);

}
}


#2

Comparisons produce booleans. If you already have a boolean, then you don't need to do a comparison because.. you have a boolean already.

HashMap's method for accessing values by key is get, and since a book in that loop is a String, it won't have a getValue method.

You might wanna specify that your HashMap maps from String to Boolean.

your getFinishedBooks's parameter specifies a type, but not a name. Also, the type should be more specific (String to Boolean)

books.getKey(): books is a string here, it has no such method. It's also the key itself, so you don't need to do anything with it


#3
for(String book:library.keySet())
{
   System.out.println(book);
}

With this code I can print all the books of the library. But how can I print only the ones which are read? Thank you!


#4

Where does it say if they have been read? Can you use the keys to get at that information?


#5

I was able to get the true books to print using the code below.

import java.util.HashMap;

public class Library {

public Library() {

}

public void getFinishedBooks(HashMap library) {
if (library.size() < 1) {
System.out.println("The library is empty!");
} else {

for (String book: library.keySet()) {
  if (library.get(book) == true){
  System.out.println(book);
  }
 }

}
}

public static void main(String[] args) {
HashMap myBooks = new HashMap();
myBooks.put("Road Down The Funnel", true);
myBooks.put("Rat: A Biology", false);
myBooks.put("TimeIn", true);
myBooks.put("3D Food Printing", false);

Library myLibrary = new Library();
myLibrary.getFinishedBooks(myBooks);
}
}