Page 1 of 5 123 ... LastLast
Results 1 to 20 of 93
Like Tree4Likes

Thread: adding an object to an array in another class

  1. #1
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default adding an object to an array in another class

    I am so confused I want to cut my own throat!!!

    Here are the instructions for this method:


    1. The Hotel will have an addRoom method that will create each room with the required information: room number, bed type, smoking/non-smoking, and the room rate. Create at least 5 rooms with different characteristics. Each room will also have a boolean field called occupiedattribute that will be set to false when the room is created. Don't forget to increment the numOfRooms instance variable. Example values for the rooms are:

    101 queen s 100
    102 king n 110
    103 king n 88
    104 twin s 100
    105 queen n 99


    Java Code:
    public class Hotel	{
    	   /**
    		*/
      	 	private Room[]theRooms; 		
    		/**
    		*/
    		private String name;
    		
    		/**
    		*/
    		private String location;
    		
    		/**
    		*/
    		private int occupiedCnt;
    		
    		/**
    		*/
    		private int numOfRooms;
    		
    		/**
    		*/
    		Room newRoom = new Room();
    		
    		
    		/**
    		*/
    		public Hotel()
    		{
    		   Room[] theRooms = new Room[10];
    			name = "";
    			location = "";
    			occupiedCnt = 0;
    			numOfRooms = 10;
    		}
    		
    				
    		/**
    		*/
    		public Hotel(String aName, String aLocation)
    		{
    			Room[] theRooms = new Room[10];
    			name = aName;
    			location = aLocation;
    			numOfRooms = 0;
    		}
    		
    		/**
    		*/
    		public void addRoom(int roomNum, String bedType, char smoking, double rate)
    		{
                            theRooms[i]=newRoom;
    			newRoom.setOccupied(false);
    			numOfRooms++;
    		}
    So what I am trying to figure out is how to I set up the addRoom method to automatically add the room to the array when I call it in the tester class? Also, if each room is ((int roomNum, String bedType, char smoking, double rate) how do I add the boolean field occupied to the room object in the array?

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,016
    Rep Power
    6

    Default Re: adding an object to an array in another class

    The code is a bit off. If you look at your "no-args" constructor, numOfRooms is initialized to 10. But if you look at your second constructor, numOfRooms is all of a sudden initialized to 0. I would expect the exact same thing in both constructors, which is to set it to zero based on the problem description ("don't forget to increment numOfRooms"). I would expect that newRoom to be constructed INSIDE the addRoom() method, it has no business being a member of your class.

    Just explain what the code has to do in words.

    The first room needs to go in index 0 of the array
    the second room needs to go in index 1 of the array
    the third room needs to go in index 2 of the array

    Isn't there something in your class that can help you determine which index you need to use to store the new room?
    jwood likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    Thanks! I think I got it...at least it compiles now.

    Java Code:
     
    Room thisRoom = new Room();                   
    thisRoom.setOccupied(false);
    theRooms[numOfRooms]=thisRoom;
    numOfRooms++;

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,016
    Rep Power
    6

    Default Re: adding an object to an array in another class

    Getting it to compile is only a quarter of the battle ;)

    If you also understood how you can reason about how to solve these kind of things for yourself, that would be awesome.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    Well crud. Working on the tester and this method is causing an error...

    Tester:
    Java Code:
    public class HotelTest
       {
           public static void main(String[] args)
          {
    			Hotel newHotel = new Hotel("Margaritaville", "Pensacola Beach");
    			newHotel.addRoom(101, "queen", 's', 100);   //ERROR
    			newHotel.addRoom(102, "king", 'n', 110);
    			newHotel.addRoom(103, "king", 'n', 88);
    			newHotel.addRoom(104, "twin", 's', 100);
    			newHotel.addRoom(105, "queen", 'n', 99);
    			newHotel.addReservation("Wood", 'n', "king");
    			newHotel.addReservation("Cox", 'n', "queen");
    			newHotel.addReservation("Murrary", 'n', "twin");
    			//newHotel.cancelReservation(Cox);
    			System.out.println(newHotel.cancelReservation("Cox"));
    			newHotel.printReservationList();
    			System.out.println("Daily Sales: " + newHotel.getDailySales());
    			System.out.printf("Occupancy Percentage: " + newHotel.occupancyPercentage( + '\n'));
    			Hotel newHotel2 = new Hotel();
    			newHotel2.addName("Merriott");
    			newHotel2.addLocation("Pensacola");
    			System.out.println(newHotel2.getName() + "," + newHotel2.getLocation());
    		}
    	}

    method:

    Java Code:
    public void addRoom(int roomNum, String bedType, char smoking, double rate)
    		{  
    			//for(int i = 0; i < theRooms.length; i++)
    			{	
    				int i = numOfRooms;
    				Room newRoom = new Room();	
    				newRoom.setOccupied(false);
    				theRooms[i] = newRoom;     //ERROR
    				numOfRooms++;
    			}
    		}
    Error:
    Exception in thread "main" java.lang.NullPointerException
    at Hotel.addRoom(Hotel.java:70)
    at HotelTest.main(HotelTest.java:16)

    I have marked which lines the error is referencing in the codes. I am guessing the addRoom method is not assigning the room object to the array?

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,610
    Rep Power
    5

    Default Re: adding an object to an array in another class

    You Hotel constructors are shadowing (hiding) the theRooms instance field by redeclaring it.

    Java Code:
    //Replace this :
    
    Room theRooms[] = new Room[10];
    
    //with this:
    
    theRooms[] = new Room[10];

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    When I do that in the constructors I get not a statement errors....

    Java Code:
    Hotel.java:43: error: not a statement           
               theRooms[] = new Room[10];
                           ^
    Hotel.java:43: error: ';' expected
               theRooms[] = new Room[10];
                              ^
    Hotel.java:43: error: not a statement
               theRooms[] = new Room[10];
                                               ^
    Hotel.java:55: error: not a statement
                theRooms[] = new Room[10];
                            ^
    Hotel.java:55: error: ';' expected
                theRooms[] = new Room[10];
                               ^
    Hotel.java:55: error: not a statement
                theRooms[] = new Room[10];
                                     ^

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,610
    Rep Power
    5

    Default Re: adding an object to an array in another class

    Ugh!! Sorry I made a mistake. Get rid of the [] on the left of the equals.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  9. #9
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    in the constructors? so Room theRooms = new Room[10]; that results in incompatible types error

  10. #10
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    Here are my directions for the constructors and the addRoom method if that helps any....


    1. The Hotel class has two constructors
      1. A default constructors that sets the Array to a size of 10 and all instance fields to a default value. We will not be using this constructor but you should almost always have one.
      2. The Hotel class parameterized constructor will read in the hotel name and location from hard-coded values in the tester class, such as Beach Marriot Pensacola, it will also assign numOfRooms to zero. numOfRooms indicates how many rooms are in the hotel. It will create a 10 element array.

    2. The Hotel will have an addRoom method that will create each room with the required information: room number, bed type, smoking/non-smoking, and the room rate. Create at least 5 rooms with different characteristics. Each room will also have a boolean field called occupiedattribute that will be set to false when the room is created. Don't forget to increment the numOfRooms instance variable. Example values for the rooms are:

    101 queen s 100
    102 king n 110
    103 king n 88
    104 twin s 100
    105 queen n 99

  11. #11
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    OK, I changed my constructors to

    Java Code:
    this.theRooms = new Room[10];
    and the tester runs through the addRoom part of the tester.

    Now I am getting the same error Exception in thread "main" java.lang. with the addReservation method on line 5....

    Java Code:
    public void addReservation(String occName, char resSmoke, String resBedType)
            {    
                for(int i = 0; i < theRooms.length; i++)
                {
                    if(theRooms[i].getSmoking() == resSmoke && theRooms[i].getBedType() .equals(resBedType))
    
      //ERROR
                    {
                        newRoom.setOccupant(occName);
                        newRoom.setOccupied(true);
                        System.out.println("Reservation Made.");
                        occupiedCnt++;
                    }
                    else
                    {    
                        System.out.println("No reservation made.");
                    }
                }
            }

    Tester:
    Java Code:
    public class HotelTest
       {
           public static void main(String[] args)
          {
                Hotel newHotel = new Hotel("Margaritaville", "Pensacola Beach");
                newHotel.addRoom(101, "queen", 's', 100);
                newHotel.addRoom(102, "king", 'n', 110);
                newHotel.addRoom(103, "king", 'n', 88);
                newHotel.addRoom(104, "twin", 's', 100);
                newHotel.addRoom(105, "queen", 'n', 99);
                newHotel.addReservation("Wood", 'n', "king");
                newHotel.addReservation("Cox", 'n', "queen");
                newHotel.addReservation("Murrary", 'n', "twin");
                //newHotel.cancelReservation(Cox);
                System.out.println(newHotel.cancelReservation("Cox"));
                newHotel.printReservationList();
                System.out.println("Daily Sales: " + newHotel.getDailySales());
                System.out.printf("Occupancy Percentage: " + newHotel.occupancyPercentage( + '\n'));
                Hotel newHotel2 = new Hotel();
                newHotel2.addName("Merriott");
                newHotel2.addLocation("Pensacola");
                System.out.println(newHotel2.getName() + "," + newHotel2.getLocation());
            }
        }
    Which kind of confuses me : Here is everything when it runs:

    Reservation made for Wood
    Reservation made for Wood
    No reservation made for Wood
    No reservation made for Wood
    Exception in thread "main" java.lang.NullPointerException
    at Hotel.addReservation(Hotel.java:117)
    at HotelTest.main(HotelTest.java:21)
    Last edited by jwood; 07-31-2013 at 12:09 AM.

  12. #12
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    OK, fixed the exception, but I am not getting the anticipated results.....

    Java Code:
    public void addReservation(String occName, char resSmoke, String resBedType)
    		{	
    			for(int i = 0; i <= theRooms.length; i++)
    			{
    				if(theRooms[i].getSmoking() == resSmoke && theRooms[i].getBedType().equals(resBedType))
    				{
    					theRooms[i].setOccupant(occName);
    					theRooms[i].setOccupied(true);
    					System.out.println("Reservation made for " + occName);
    					occupiedCnt++;
    					return;
    				}
    				else
    				{	
    					System.out.println("No reservation made for " + occName);
    					return;
    				}
    			}
    		}

    Results:
    No reservation made for Wood
    No reservation made for Cox
    No reservation made for Murrary


    The only no should be Murrary....

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,610
    Rep Power
    5

    Default Re: adding an object to an array in another class

    Ok, it is somewhat hard to follow this but here is how I see it.

    1. You can have at most 10 rooms.
    2. You add a room and increment numOfRooms.
    3. But when you addReservation, you iterate thru the array size and not numOfRooms size.
    4. And since you start at 0, go to < numOfRooms, not <= numOfRooms

    What I suggest you do is to test each class separately, if possible. First, test the Room class to see if it is constructing them okay. Then check out the Hotel class to see if it is simply creating a hotel with rooms. Iterate thru the rooms before you add patrons to see if they are being created correctly. If you break down the various classes and methods and try testing them individually (also use print statements to assist) it will increase the chances of everything working together smoothly.

    I also recommend you override toString() in each of your classes. Do it so it returns a string of useful information when you pass a class reference to a print statement.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  14. #14
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    Thanks for the 4. And since you start at 0, go to < numOfRooms, not <= numOfRooms. That makes way more sense than what I was doing!
    Last edited by jwood; 07-31-2013 at 07:07 AM.

  15. #15
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    YIPEE!!!!! I figured it out!! I was doing an if/else instead of a linear search so it was printing a response for each element of the array!

  16. #16
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    OK a new one:

    Java Code:
    public String cancelReservation(String cOccName)
            {    
                int i = findReservation(cOccName);
                if(i >= 0)
                {
                    theRooms[i].setOccupied(false);
                    occupiedCnt--;
                    return("Reservation cancelled for " + cOccName);
                }
                else
                {
                    return("Reservation not found for " + cOccName);
                }            
            }
            
            /**
            */
            private int findReservation(String occName)
            {    
                int index;
                for(int i = 0; i < numOfRooms; i++)
                {
                    if(theRooms[i].getOccupant().equals(occName))
                    {
                        index = i;
                        return index;
                    }
                }
                index = NOT_FOUND;
                return index;                    
            }

    Error:
    Exception in thread "main" java.lang.NullPointerException
    at Hotel.findReservation(Hotel.java:160)
    at Hotel.cancelReservation(Hotel.java:140)


    at lines 23 and 3

    I really struggled with these two methods and they do compile fine. I think the exception for both is based on line 23. Since the findReservation is only called/activated in the cancelReservation method the parameter is only entered when the cancel method is run in the tester. I think I am not telling the find method that its parameter IS the parameter of the cancel method....

  17. #17
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default Re: adding an object to an array in another class

    Do all the rooms even have an occupant? If the parameter occName shouldn't ever be null, then reverse the equals(...) comparison.

    And when posting snippets along with a stack trace, please indicate by inline comments which were the lines the numbers of which appear in the trace.

    In the snippet you posted, the concerned lines aren't even 20 lines apart.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  18. #18
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    Quote Originally Posted by DarrylBurke View Post
    Do all the rooms even have an occupant? If the parameter occName shouldn't ever be null, then reverse the equals(...) comparison.

    And when posting snippets along with a stack trace, please indicate by inline comments which were the lines the numbers of which appear in the trace.

    In the snippet you posted, the concerned lines aren't even 20 lines apart.

    db
    I thought I did specify which lines....

    at lines 23 and 3
    next time I will put it right next to the error code.


    That switch solved my issue. Thanks! I would never have thought of that!

  19. #19
    jwood is offline Senior Member
    Join Date
    Jun 2013
    Posts
    136
    Rep Power
    0

    Default Re: adding an object to an array in another class

    BLEH...I am yet lost again. In my Hotel class we are instructed to create an Array of instances of class Room to hold information about each room. The outline show us setting it up as an instance variable. So in my Hotel class I have this:

    Java Code:
    private Room[]theRooms;
    Now in my Room class I have a toString method:
    toString() provides all the details of a room - room number, name of guest(if occupied) , bed type, smoking/non-smoking, rental rate. This should all be formatted nicely with one attribute on each line using the '\n' escape character.

    Java Code:
    public  String toString()	  	{			
    			return("Room Number: " + getRoomNum() + '\n' + "Occupant name: " + getOccupant() + '\n' + "Smoking Room: " + 
    									getSmoking() + '\n' + "Bed Type: " + getBedType() + '\n' + "Rate: " + getRoomRate() + '\n' + '\n');
    	  	}
    I have realized, as I work through my tester, that I need the toString method to return based on the iterations of the array. Now the Room class toString method is only called in the Hotel class

    Like here:
    Java Code:
    public void printReservationList()		{  
                            System.out.println("Reservation List");
    			for(int i = 0; i < theRooms.length; i++)
    			{
    				if(theRooms[i].isOccupied()==true)
    					
    					System.out.print (newRoom.toString());	
    			}
    		}

    Right now it is simply returning blank values:



    Room Number: 0
    Occupant name:
    Smoking Room:
    Bed Type:
    Rate: 0.0

  20. #20
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,016
    Rep Power
    6

    Default Re: adding an object to an array in another class

    Well then apparently there is a Room object there, but its not initialized properly. Is your addRoom() method actually setting the smoking/bed type/rate properties?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Page 1 of 5 123 ... LastLast

Similar Threads

  1. null pointer when adding object into an array
    By NoobieCode in forum New To Java
    Replies: 6
    Last Post: 07-24-2013, 11:58 PM
  2. Replies: 15
    Last Post: 08-19-2011, 03:08 AM
  3. help adding to array from another class
    By Grid_iso in forum New To Java
    Replies: 0
    Last Post: 05-09-2011, 10:00 AM
  4. Replies: 1
    Last Post: 05-04-2010, 11:00 AM
  5. Adding elements to an Object Array
    By aneesahamedaa in forum New To Java
    Replies: 4
    Last Post: 09-07-2008, 03:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •