Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

For...each loop problem

  • 20-04-2011 10:36am
    #1
    Registered Users, Registered Users 2 Posts: 79 ✭✭


    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");
    }

    Any help is appreciated.


Comments

  • Registered Users, Registered Users 2 Posts: 4,277 ✭✭✭km991148


    ok.. I dont know Java... but taking a guess on what a hash map is - I think you are trying to iterate over the keys AND values... see the second answer here:

    http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap

    this outlines the correct syntax in the third example (1 and 2 are the keys/values only)..

    hth;


  • Registered Users, Registered Users 2 Posts: 2,013 ✭✭✭lynchie


    What is the definition of properties?


  • Registered Users, Registered Users 2 Posts: 183 ✭✭selfdiy


    If properties is a hashmap then something like this should work


    Map<Integer, String> p = new HashMap<Integer, String>();
    p.put(1, "java");
    p.put(2, "rocks");
    for(String str : p.values()){
    System.out.println("String is " +str);
    }


  • Registered Users, Registered Users 2 Posts: 240 ✭✭Axe Rake



    //create HashMap object
    HashMap hMap = new HashMap();

    //add key value pairs to HashMap
    hMap.put("1","One");
    hMap.put("2","Two");
    hMap.put("3","Three");

    /*
    get Collection of values contained in HashMap using
    Collection values() method of HashMap class
    */
    Collection c = hMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through HashMap values iterator
    while(itr.hasNext())
    System.out.println(itr.next());
    }

    HashMap iteration example for printing the values.


  • Moderators, Technology & Internet Moderators Posts: 1,336 Mod ✭✭✭✭croo


    A bit of a stab in the dark here... but is property a java keyword?


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    The program I'm doing is an estate agency. Properties are just houses or apartments. And I have a HashMap that stores houses and apartments (using inheritance).

    Just can't get this method to work as it's just returning all of the properties contained in the HashMap when I only need to show the houses that are sold. So is there a way to just access the houses in the HashMap? Or some way in inheritance to do it?

    I've tried the instanceof method in Inheritance but it doesn't seem to work


  • Registered Users, Registered Users 2 Posts: 33 frezzabelle


    That's an iteration for a List. You need to iterate the map using the keys
    E.g.

    public static void printMap(Map mp) {
    * * Iterator it = mp.entrySet().iterator();
    * * while (it.hasNext()) {
    * * * * Map.Entry pairs = (Map.Entry)it.next();
    * * * * System.out.println(pairs.getKey() + " = " + pairs.getValue());
    * * }
    }
    Maybe check the status while in each iteration?


  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    That's an iteration for a List. You need to iterate the map using the keys
    E.g.

    public static void printMap(Map mp) {
    * * Iterator it = mp.entrySet().iterator();
    * * while (it.hasNext()) {
    * * * * Map.Entry pairs = (Map.Entry)it.next();
    * * * * System.out.println(pairs.getKey() + " = " + pairs.getValue());
    * * }
    }
    Maybe check the status while in each iteration?

    Ok thank you for the help. But how do I work iteration into the code I have? I'm not very familiar with the iterator.


  • Registered Users, Registered Users 2 Posts: 183 ✭✭selfdiy


    A bit of a stab in the dark here, but would the following work.
    /**
    * Displays the number of houses that are sold.
    */
    public void displaySoldHouses()
    {
    int count = 0;
    for(Property property : properties.values){
           if (property instanceof House){
                 House house = (HOUSE) property;
                 if(house.isSold()){
                      count++; 
                 }
           }
    }
    


  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    selfdiy wrote: »
    A bit of a stab in the dark here, but would the following work.
    /**
    * Displays the number of houses that are sold.
    */
    public void displaySoldHouses()
    {
    int count = 0;
    for(Property property : properties.values){
           if (property instanceof House){
                 House house = (HOUSE) property;
                 if(house.isSold()){
                      count++; 
                 }
           }
    }
    

    Thanks for the help, but I am still getting an error message "foreach not applicable to expression type" so I have come to the conclusion that I can't use a foreach loop for this as I always get that error message.

    I have tried making a set of the properties in the hashmap and then finding out what ones are sold but i dont know how to access only the ones that are houses.

    Here is the code:
    /**
         * 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!");
            }
        }
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 183 ✭✭selfdiy


    If you could post your Property and House class.
    I should be able to whip up an example....


  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    selfdiy wrote: »
    If you could post your Property and House class.
    I should be able to whip up an example....

    Class Property
    public class Property implements Serializable
    {
        private String propertyId;
        private String address;
        private int numberOfBedrooms;
        protected double sellingPrice;
        private boolean sold;
        private Buyer buyer;
        protected static double stampDuty = 0.20;
       
        /**
         * Constructor for objects of class Property
         */
        public Property(String propertyId, String address, int numberOfBedrooms, double sellingPrice)
        {
            if (propertyId == " ") {
                System.out.println("A property's ID can't be blank");
            }
            else {
                this.propertyId = propertyId;
                this.address = address;
                this.numberOfBedrooms = numberOfBedrooms;
                this.sellingPrice = sellingPrice;
            }
        }
        /**
         * Gets the property's id.
         */
        public String getId()
        {
            return propertyId;
        }
        
        /**
         * Gets the address of the property.
         */
        public String getAddress()
        {
            return address;
        }
        
        /**
         * Gets the number of bedrooms that the house has.
         */
        public int getNumberOfBedrooms()
        {
            return numberOfBedrooms;
        }
           
        /**
         * Gets the selling price of the property.
         */
        public double getSellingPrice()
        {
            return sellingPrice;
        }
        
        /**
         * Shows the buyer of a property, if there is one.
         */
        public Buyer getBuyer()
        {
            if (buyer != null) {
                return buyer;
            }
            return null;
        }
        
        /**
         * Calculates the price for a property.
         */
        public double calculatePrice()
        {
            sellingPrice = sellingPrice + (sellingPrice * stampDuty);
            return sellingPrice;
        }
        
        /**
         * Changes the selling price of the house.
         */
        public void changeSellingPrice(double sellingPrice)
        {
            this.sellingPrice = sellingPrice;
        }
        
        /**
         * Assigns a property to a buyer (sold).
         */
        public void setSold(boolean sold)
        {
            this.sold = true;
        }
           
        /**
         * Checks to see if the property is sold or not.
         */
        public boolean isSold()
        {
          return sold;
        } 
        
        /**
         * Sells a property - house or apartment.
         */
        public void sellProperty(Buyer buyer)
        {
          NumberFormat cf = NumberFormat.getCurrencyInstance();
            if (buyer != null) {
              if (buyer.getAmountOfMoney() > calculatePrice()) {
                setSold(true);
                this.buyer = buyer;
                System.out.println("The full cost of the property was " + cf.format(calculatePrice()));
             }
            else {
                System.out.println("The buyer can't afford to buy that property");
                System.out.println("The total cost of this property is: " + cf.format(calculatePrice()));
                System.out.println("The buyer's funds are: " + buyer.getAmountOfMoney());
             }
          }
          else {
              System.out.println("No buyer object was found");
            }
        }   
        
        /**
         * Returns a String of the details of the property and buyer.
         */
        public String toString()
        {
            NumberFormat cf = NumberFormat.getCurrencyInstance();
            String returnString = "";
            returnString = returnString + "\nProperty Id: " + propertyId + " ";
            returnString = returnString + "\nProperty Address: " + address + " ";
            returnString = returnString + "\nNumber of Bedrooms: " + numberOfBedrooms + " ";
            returnString = returnString + "\nSelling Price: " + cf.format(sellingPrice) + " ";
            if (sold) {
                returnString = returnString + "\nThe buyer's details are: ";
                returnString = returnString + buyer.toString();
            }
            else {
                returnString = returnString + "\nThis property has not been sold";
            }
            return returnString;
        }
    

    Class House
    public class House extends Property
    {
       
        /**
         * Constructor for objects of class House
         */
        public House(String propertyId, String address, int numberOfBedrooms, double sellingPrice)
        {
           super(propertyId, address, numberOfBedrooms, sellingPrice); 
        }
         /**
         * Returns a String of the details of a house.
         */
        public String toString()
        {
            NumberFormat cf = NumberFormat.getCurrencyInstance();
            String returnString = super.toString();
            return returnString;
        }
        
    }
    


  • Registered Users, Registered Users 2 Posts: 89 ✭✭tehjimmeh


    Princess3 wrote: »
    Thanks for the help, but I am still getting an error message "foreach not applicable to expression type" so I have come to the conclusion that I can't use a foreach loop for this as I always get that error message.

    I have tried making a set of the properties in the hashmap and then finding out what ones are sold but i dont know how to access only the ones that are houses.

    Here is the code:
    /**
         * 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 haven't read the thread much, but why not:
    /**
         * 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) {
                   Property p = properties.get(id);
                   if ((p instanceof House ) && p.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!");
            }
        }
    


  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    tehjimmeh wrote: »
    I haven't read the thread much, but why not:
    /**
         * 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) {
                   Property p = properties.get(id);
                   if ((p instanceof House ) && p.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!");
            }
        }
    

    THANK YOU!! That method is perfect thanks, I have tested it, and it seems to work but the only problem left is that it isn't adding 1 to count each time it comes across a house that is sold. I have no idea why, I even did the debugger on it and wasn't able to figure it out. I'll keep trying but thanks so much!! :)


  • Registered Users, Registered Users 2 Posts: 183 ✭✭selfdiy


    Here's an alternative using the classes you provided,

    Also just when it comes to dealing with money amounts in Java, use BigDecimal as Doubles aren't accurate enough.

    http://blogs.sun.com/CoreJavaTechTips/entry/the_need_for_bigdecimal

    public class TestHouse {
    	
    	
    	public static void main(String args[]){
    		
    		Property one = new House("1", "Address", 3, 500000);
    		Property two = new House("2", "Address", 4, 600000);
    		two.setSold(true);
    		
    		
    		Map<String, Property> properties = new HashMap<String, Property>();
    		
    		properties.put("1",one);
    		properties.put("2",two);
    
    		
    		int count = 0;
    		for(Property property : properties.values()){
    		       if (property instanceof House){
    		             House house = (House) property;
    		             if(house.isSold()){
    		                  count++; 
    		                  System.out.println("House "+house.getId()+" is sold");
    		             }
    		       }
    		}
    		
    		
    		
    	}
    
    }
    


  • Moderators, Technology & Internet Moderators Posts: 1,336 Mod ✭✭✭✭croo


    croo wrote:
    A bit of a stab in the dark here... but is property a java keyword?
    Princess3 wrote: »
    The program I'm doing is an estate agency. Properties are just houses or apartments. And I have a HashMap that stores houses and apartments (using inheritance).....
    Yeah that was clear :D
    Property/Properties are, I'm sure, also keywords used in Java (or J2ee anyway). I wasn't sure if there were any restriction on the use of the keyword so it was a "just in case" comment as I didn't have time to check.
    I see you got your answer so all is well.


  • Registered Users, Registered Users 2 Posts: 2,265 ✭✭✭Seifer


    Neither "property" nor "properties" are keywords in Java.

    http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

    Java EE


  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    Seifer wrote: »
    Neither "property" nor "properties" are keywords in Java.

    http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

    Java EE

    I know...
    Property is one of the names of my classes and properties is the name of the HashMap of my properties


  • Registered Users, Registered Users 2 Posts: 2,265 ✭✭✭Seifer


    Princess3 wrote: »
    I know...
    Property is one of the names of my classes and properties is the name of the HashMap of my properties
    I was referring to the post above mine, not your original post.


  • Moderators, Technology & Internet Moderators Posts: 1,336 Mod ✭✭✭✭croo


    Seifer wrote: »
    Neither "property" nor "properties" are keywords in Java.

    http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

    Java EE

    Like I said I didn't have time to check if it was an actual "keyword" ... I just knew it was used somewhere in Java, as in ...
    http://download.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html
    Obviously its use is not restricted as the OP managed to get their code working. But the use of the class called Property caught my attention and I mentioned it "just in case"!


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 79 ✭✭Princess3


    Thanks everyone for your help.
    I have it working perfectly now :) really appreciate the help!!


Advertisement