Personal library project - Hash.Map & if


#1

Hello,

It seems i don’t understand how to use the values of a Hash.Map in a conditional statement. :thinking:

Here’s my code :

import java.util.HashMap;

public class Library {
  public Library () {}
  
  public void getFinishedBooks (HashMap<String, Boolean> library) {
    if (library.size() < 1) {
      System.out.println("The library should not be empty.");
    }
    else {
      for (String book : library.keyset()) {
        if (Boolean library.get() == true) {
          System.out.println (book);
        }
      }
    }
  }
  
  public static void main (String[] args) {
    Hash.Map<String, Boolean> myBooks = new Hash.Map<String, Boolean>();
    myBooks.put("Road Down The Tunnel", true);
    myBooks.put("Rat: A Biology", false);
    myBooks.put("TimeIn", true);
    myBooks.put("3D Food Printing", false);
    Library myLibrary = new Library ();
    myLibrary.getFinishedBooks (myBooks);
  }
}

And my errors :

Library.java:12: error: ‘)’ expected
if (Boolean library.get() == true) {
^
Library.java:12: error: not a statement
if (Boolean library.get() == true) {
^
Library.java:12: error: ‘;’ expected
if (Boolean library.get() == true) {
^
3 errors

Thank you for your time.


#2

maybe first see what values the loop gives you:

for (String book : library.keyset()) {
    System.out.println(book);
}

then realize you have the key, how to get the value to check the status? Not sure, i would have to see the instructions (please include url of project/exercise)


#3

Oh yes. Of course. Here it is :

https://www.codecademy.com/courses/learn-java/projects/personal-library

Watch the steps 8 & 9.

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

The values are boolean type and i want to verify if they are true. I suppose i don’t use the library.get() correctly?


#4

a hashmap consist of keys and values. We create a for loop to get the keys (book), then we can use the key to retrieve the associated value.

the instruction mention this:

first check the completion status of each book

you understand book and the for loop?


#5

Ok. I finally see and understand my mistakes.
1/ keySet and not keyset.
2/ if (library.get(book) == true)
I thought the .get() method could work like the .keyset() method and get us the set of values without parameter.

Now it works.

Thank you.