1 Error on line 13(CodeAcademy Learn Java, personal library)


#1



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


On line 13, there is one error!
Library.java:13: error: incompatible types: String cannot be converted to Boolean
for(Boolean book : library.keySet()){


import java.util.HashMap;
import java.lang.Iterable;

class Library{
  public Library(){
    
  }
  public void getFinishedBooks(HashMap<String, Boolean> library){
    if(library.size() < 1){
      System.out.println("Error! HashMap is empty.");
    }
    else{
      for(Boolean book : library.keySet()){
        if(book=true){         
          System.out.println(book);
        }
      }
    }
    
  }
  public static void main(String[] args){
    HashMap<String, Boolean> myBooks = new HashMap<String, Boolean>();
    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

You're iterating over the key set of the map. Since the map maps Strings to Booleans, its keys are Strings and its values are Booleans. So since you're iterating over the keys, your iteration variable (i.e. book) needs to have the type String.

This then also means that you can't compare it to true on the next line. You'll need to fetch its associated value first and compare that to true.

Speaking of that line: = is the assignment operator, == is the equality operator. So if you want to check whether two values equal each other, you should write if(x == y), not if(x = y).

However in the case where y is true you can just write if(x) as there is no possible value of x that would lead to the expressions x and x == true to have different values (if x is true, x == true is also true, if x is false, x == true is also false (and if x is anything else, if(x) and if(x == true) are both type errors).


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.