Results 1 to 5 of 5
- 04-21-2011, 01:32 AM #1
Member
- Join Date
- Apr 2011
- Posts
- 3
- Rep Power
- 0
For... Each loop problem using hash map
I am currently doing an estate agency java project. I have properties and buyers both stored in two different Hash Maps. In the following method I am trying to display the number of sold houses (there is a buyer).
I keep getting an error message saying: for each not applicable to expression type.
Here is my code:
/**
* Displays the number of houses that are sold.
*/
public void displaySoldHouses()
{
int count = 0;
for (Property property : properties) {
if (property instanceof House && property.isSold()) {
count = count + 1;
}
}
System.out.println("You own " + count + " houses");
}
OR because it's a hash map do I need to create a set like in this alternative method:
/**
* Displays the total number of houses which have been sold.
*/
public void displayHousesSold()
{
int count = 0;
if (!properties.isEmpty()) {
Set <String> keys = properties.keySet();
for (String id : keys) {
if (properties.get(id).isSold()) {
count = count + 1;
}
else {
System.out.println("There are no houses sold");
}
}
System.out.println("The number of sold houses are: " + count);
}
else {
System.out.println("There are no properties in the HashMap!");
}
}
I have tried the method above, it compiles perfectly but I don't know how to access just the House objects in the hash map as the hash map contains apartments too and I just need the house ones for this method. It just returns the number of properties sold overall but i only need to show the amount of sold houses.
Any help is appreciated.
- 04-21-2011, 01:52 AM #2
The for each loop only works with classes that implement the Iterable interface. I believe HashMap doesn't. However you can get a Set from the Map which does implement Iterable.
- 04-21-2011, 02:05 AM #3
Member
- Join Date
- Apr 2011
- Posts
- 3
- Rep Power
- 0
Yeah that's what I was thinking thank you. So the second method I provided would be more correct then. But how do I only access the properties that are houses?
- 04-21-2011, 02:26 AM #4
If House is a subclass of Property then you can use the instanceof operator.
- 04-21-2011, 10:41 AM #5
Member
- Join Date
- Apr 2011
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
Identifying comments in data with a hash. Problem with delimiter?
By adwodon in forum New To JavaReplies: 2Last Post: 03-11-2011, 05:22 AM -
problem with loop (maybe?)
By jdg951 in forum New To JavaReplies: 7Last Post: 12-08-2010, 10:32 AM -
simple line problem / for loop problem
By helpisontheway in forum New To JavaReplies: 1Last Post: 11-17-2009, 06:12 AM -
Hash
By sandy1028 in forum New To JavaReplies: 4Last Post: 04-17-2009, 10:36 AM -
Hash Map
By rekha in forum New To JavaReplies: 1Last Post: 03-21-2009, 01:00 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks