For each


#1

how do for-loops with ‘:’ work and in what case is it required to use ‘.keySet()’?

Earlier in the course i had to use something like

for (String grade : grades.keySet()) {}

but just know i had an error that i was only able to fix by watching the attached video.
The suggested solution in this example doesn’t use ‘.keySet()’.

for (Integer grade : grades) {}

is the datatype the decisive factor for when ‘.keySet()’ is required?


#2

the for loop consist of two parts. On the left the variable which java will assign the values to, on the right what you want to loop over:

for (Integer grade : grades) {
    System.out.println(grade);
}

will print each grade of the grades array/arraylist

keySet is a method for hashmap:

https://www.tutorialspoint.com/java/util/hashmap_keyset.htm


#3

Okay that’s good to know. But apparently i still don’t know how to make the for loops work.
Would you mind to look at this?

public void getFinishedBooks(HashMap<String, Boolean> library) {

     for (String book : library.setKey()) {
        
        //if ()
        System.out.println(book);
        
      }
}

#4

can have the exercise url? Then i can actually run the code, that is a lot easier for debugging

and your whole code, maybe the mistake is not even within this method


#5

Sure, it’s: https://www.codecademy.com/courses/learn-java/projects/personal-library

import java.util.HashMap;

// Hey, this is library!
public class Library {
  
  public Library() {}
  
  public void getFinishedBooks(HashMap<String, Boolean> library) {
    
    if (library.size() < 1) {
      
      System.out.println("Error! The hashmap 'library' is empty.");
      
    }	else {
      
      for (HashMap<String> book : library.setKey()) {
        
        // if () 
        System.out.println(book);
        
      }
      
    }
    
  }
  
}

#6

setKey? You mean keySet(), quite a differences there

the keySet() method gives you the keys of hasmhap, which are strings, so book should be of type string

and there is no main method in your code? Every java program needs a main method


#7

Thank you very much! No more errors :slight_smile:


#8

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