Java code error (I can't figure out what's wrong with it)


#1

import java.util.HashMap;

public class Library {

Library() {

}
public void getFinishedBooks(HashMap<String, Boolean> library) {
if (library < 1) {
System.out.println(“HashMap is empty”);
} else {
for (String book : library) {
if (library = true) {
System.out.println(book);
}
}
}
}
public static void main(String args[]) {
HashMap<String, Boolean> myBooks = new HashMap<String, Boolean>();
myBooks.add(“Road Down The Funnel”, true);
myBooks.add(“Rat: A Biology”, false);
myBooks.add(“TimeIn”, true);
myBooks.add(“3D Food Printing”, false);
Library myLibrary = new Library();
myLibrary.getFinishedBooks(myBooks);

}
}


#2

Pls indent your code and show us the error message if there is one


#3

I’m just begining Java, so I don’t know much, but I found a site that might help:


you put in your code, click debug and it should tell you the problem! I hope it helps! :smile::+1:


#5

in method getFinishedBooks you should create if statement that checks the size of library. so it should looks like this: if (library.size()<1), because library for itself is HashMap and it contains keys and values, not one integer that you can compare with 1;
furthermore, for (String book : library.keySet()) - because method keySet returns list of keys;
and again, if (library.get(book) == true) , because library is HashMap, method get is used to access to HashMap with the key (in this case book). Operation equal to is labeled as ==
Hope that written above has sense… Cheers!


#6

I commented the error parts

import java.util.HashMap;

public class Library {

Library() {

}
public void getFinishedBooks(HashMap<String, Boolean> library) {
if (library < 1) { // Use library.size() to get the int size of the library
System.out.println(“HashMap is empty”);
} else {
for (String book : library) { // HashMap cannot be iterated through a foreach loop; use library.keySet() to get keys
if (library = true) { // = is for assignment , replace with == . use library.get(book) to get the value of the key; if(library.get(book) )
System.out.println(book);
}
}
}
}
public static void main(String args[]) {
HashMap<String, Boolean> myBooks = new HashMap<String, Boolean>();
myBooks.add(“Road Down The Funnel”, true); // HashMaps dont use add, they use put so just replace add with put
myBooks.add(“Rat: A Biology”, false);
myBooks.add(“TimeIn”, true);
myBooks.add(“3D Food Printing”, false);
Library myLibrary = new Library();
myLibrary.getFinishedBooks(myBooks);

}
}

reference:
https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html


#7

and I didn’t see all mistakes. method add is used by ArrayList to add value, in HashMap is used put
ex. myBooks.put(“TimeIn”, true);