Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: acessing ArrayList

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default acessing ArrayList

    ok i need to make an method that adds a room on the specific floor
    on each floor there can be maxRoomPerFloor rooms
    if on floor are no rooms return false on other hand return true
    @param floor is floor on witch room is added
    @param r is room that is added

    here is what i made so far


     
    import java.util.ArrayList;
    import java.util.List;
     
    public class Hotel {
    	String name;
    	String address;
    	List[] floors=new ArrayList[3]; /**floors in Hotel there are 2 floors plus a ground floor.**/
     
    	int maxRoomPerFloor=4; /** max number rooms per floor*/
     
     
            public Hotel(String name, String address){
    		this.name=name;
    		this.address=address;
    	}
     
    public boolean addRoom(int floor, Room r){
    		int roomPerFloor1;
    		int roomPerFloor2;
    		int roomPerFloor3;
    		for(int i=0;i<floors.length;i++){
    				if((floors[i]=floor)  && 
    				   (roomPerFloor1<maxRoomPerFloor)&&
    				   (roomPerFloor2<maxRoomPerFloor)&&
    				   (roomPerFloor3<maxRoomPerFloor)){
    					floors[i].add(r);
     
    					switch (floor) {
    		            case 1:  roomPerFloor1++;
    		                     break;
    		            case 2:  roomPerFloor2++;
                        		break;
    		            case 3:  roomPerFloor3++;
                        		break; 
    		            default: 
                        break;		
    				    }
    				}
    				if((roomPerFloor1>maxRoomPerFloor) || 
    				  (roomPerFloor2>maxRoomPerFloor) || 
    				  (roomPerFloor3>maxRoomPerFloor)){
    					return false;
    				}
    		}
    		return true;
     
    	}

    in the first if statement if(floors[i]=floor) is giving me error saying canot convert from int to List, so how do i access the element in List?


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    (floors[i]=floor)
    Does this do what you wanted? Did you want to compare floors[i] to floor, or set floors[i] to floor?


    so how do i access the element in List?
    The same way you access an element in any list.
    myListName[indexNumberOfElementNeeded]
    just like floors[i]



    (roomPerFloor1<maxRoomPerFloor)&&
    (roomPerFloor2<maxRoomPerFloor)&&
    (roomPerFloor3<maxRoomPerFloor)
    I see three problem with these lines of code. See the code just above those lines:
    int roomPerFloor1;
    int roomPerFloor2;
    int roomPerFloor3;
    When will 'NO VALUE' be less than maxRoomsPerFloor?

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    Quote Originally Posted by jps View Post
    Does this do what you wanted? Did you want to compare floors[i] to floor, or set floors[i] to floor?


    The same way you access an element in any list.
    myListName[indexNumberOfElementNeeded]
    just like floors[i]



    I see three problem with these lines of code. See the code just above those lines:
    When will 'NO VALUE' be less than maxRoomsPerFloor?
    I wanted to set floors[i] to floor but it giving me error
    yeah i know they have no value but i do that becouse if i set them to 0 they gonna reset every time i exit the for loop, so i think i need better implementation of this. i somehow need to check if room are full for every floor but dont know how to store them so they dont reset?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    I wanted to set floors[i] to floor
    Understood. Why is this inside an if statement as a stand alone unit. if ((floors[i]=floor) && (etc) && (etc) ) {
    It just looks to add confusion to what the code is to accomplish. I would rather see something like: if ((floors[i]=floor > 0) && (etc) && (etc)) { ...you know, some conditional rather than a stand alone assignment.



    I wanted to set floors[i] to floor but it giving me error
    //.....
    List[] floors=new ArrayList[3]
    What data type does floors contain? What data type are you trying to add to floors? The compiler is complaining that the list holds type object and you are trying to add type int. There is a way to specify the list will hold a specific type (int in this case), rather than default object.



    yeah i know they have no value but i do that becouse if i set them to 0 they gonna reset every time i exit the for loop, so i think i need better implementation of this
    Yes I agree. As soon as you correct the type error on the list, the compiler is going to bark at you for all three uses of the variables which were not initialized. They simply must be given a value before you can compare them to anything. The variables (and the values they hold) are available anywhere the variable is in scope. Keeping that in mind, realize that when you execute the body of a loop, the loop is actually exited and re-entered at the top. Visualize it like jumping into the pool (loop start), swimming to the other end (loop body), and getting out of the pool to run back to the end where you jumped in (loop restart). You dry off while you are running outside the pool (variables scope was lost).

    I hope I did not add to the confusion with the analogy, but RL duty calls and I must go. Good luck and hopefully I didn't cause more confusion.

  5. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    Quote Originally Posted by jps View Post
    Understood. Why is this inside an if statement as a stand alone unit. if ((floors[i]=floor) && (etc) && (etc) ) {
    It just looks to add confusion to what the code is to accomplish. I would rather see something like: if ((floors[i]=floor > 0) && (etc) && (etc)) { ...you know, some conditional rather than a stand alone assignment.
    Sorry actually im trying to compare them, so i found out i have to use .equals statement so it will be if((floors[i].equals(floor)) &&(...)&&(...) think is good like this
    Quote Originally Posted by jps View Post
    What data type does floors contain? What data type are you trying to add to floors? The compiler is complaining that the list holds type object and you are trying to add type int. There is a way to specify the list will hold a specific type (int in this case), rather than default object.
    i get it. It can be set like this: int[] floors=new int[3] but if i do like this i will be unable to add Object type room to the Array

    Quote Originally Posted by jps View Post
    Yes I agree. As soon as you correct the type error on the list, the compiler is going to bark at you for all three uses of the variables which were not initialized. They simply must be given a value before you can compare them to anything. The variables (and the values they hold) are available anywhere the variable is in scope. Keeping that in mind, realize that when you execute the body of a loop, the loop is actually exited and re-entered at the top. Visualize it like jumping into the pool (loop start), swimming to the other end (loop body), and getting out of the pool to run back to the end where you jumped in (loop restart). You dry off while you are running outside the pool (variables scope was lost).
    Yeah im aware of it and still i need to fix it. Im thinking what if i put them to Array?

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    i get it. It can be set like this: int[] floors=new int[3] but if i do like this i will be unable to add Object type room to the Array
    Originally the code used an ArrayList. Now the code shown here uses an array. Just to be clear, an ArrayList can be declared with a type.



    Yeah im aware of it and still i need to fix it. Im thinking what if i put them to Array?
    Any type of variable declared inside the loop will have the same problem as any other type of variable declared inside the loop. To maintain the values the variable's scope must be extended beyond the loop.

  7. #7
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    Quote Originally Posted by jps View Post
    Originally the code used an ArrayList. Now the code shown here uses an array. Just to be clear, an ArrayList can be declared with a type.
    u mean ArrayList<Type> but it cannot be int, right just String and i need to cast it right?

    Quote Originally Posted by jps View Post
    Any type of variable declared inside the loop will have the same problem as any other type of variable declared inside the loop. To maintain the values the variable's scope must be extended beyond the loop.
    So how do i solve this maybe add second inner for loop that counts rooms or
    i solve it somehow with break statement to exit for and then increase counter?

  8. #8
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    u mean ArrayList<Type> but it cannot be int, right just String and i need to cast it right?
    Yes. Also search "primitive types wrapper classes"



    So how do i solve this maybe add second inner for loop that counts rooms or
    i solve it somehow with break statement to exit for and then increase counter?
    Think about how to solve the problem in terms of solving the problem before thinking in terms of code. Organize a list of steps into a step by step solution to the problem. Then write code to follow the steps. The steps will help guide what the code logic will look like.

  9. #9
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    What if I declare the roomPerFloor1,2,3 up in the beginning and initialize them in the constructor of hotel, i assume the constructor will be called only once and maybe replace switch with if but i belive it wont make a difference and maybe make a method that increases each variable?

  10. #10
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    Did you try it? Did it work?

  11. #11
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    Actually no, i added an main method and tryed to add a room but it giving me errors
    public static void main(String[]args)throws Exception{
    		Hotel hotel=new Hotel("Hilton","Brodway 1001");
    		Room r=new Room(1,2,"view on beach");
    		hotel.addRoom(1, r);
    		for(int i=0;i<floors.length;i++){
    		System.out.println(i);}
    	}
    error is stupid null pointer exception here in method addRoom
    if((floors[i].equals(floor))
    and here in main method
    for(int i=0;i<floors.length;i++){

  12. #12
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    Did you try to println the variables and see which one(s) are null?
    If you need more help you will need to post the code and error messages.

  13. #13
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    i solved the null pointer exceptions but now it seems it isnt working properly
    the if statement if ((floors[i].equals(r)) was giving me null pointer so i changed it with if ((floors.equals(r)) where floor is: static List[] floors=new ArrayList[3];
    now im not sure what it does, help

  14. #14
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: acessing ArrayList

    Any time you make changes to the code, post the new code with your question so that everyone is looking at the same code.

  15. #15
    Junior Member
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: acessing ArrayList

    ok here the code
    import java.util.ArrayList;
    import java.util.List;
     
     
    public class Hotel {
    	private static String name;
    	private static String address;
    	static List[] floors=new ArrayList[3]; 
     
     
    	int maxRoomPerFloor=4; 
    	private static int roomPerFloor1;
    	private static int roomPerFloor2;
    	private static int roomPerFloor3;
     
    	public Hotel(String name, String address){
    		this.name=name;
    		this.address=address;
    		roomPerFloor1=0;
    		roomPerFloor2=0;
    		roomPerFloor3=0;
    	}
    	public int getroomPerFloor2(){
    		return roomPerFloor2;
    	}
    	public int getroomPerFloor1(){
    		return roomPerFloor2;
    	}
    	public int getroomPerFloor3(){
    		return roomPerFloor2;
    	}
    	public void incroomPerFloor1(){
    		roomPerFloor1++;
    	}
    	public void incroomPerFloor2(){
    		roomPerFloor2++;
    	}
    	public void incroomPerFloor3(){
    		roomPerFloor3++;
    	}
     
     
        public static String getName() {
    		return name;
    	}
     
    	public static String getAddress() {
    		return address;
    	}
     
    	public String toString() {	
    		return "Hotel "+getName()+" is at address "+ getAddress() ;
    	}
     
     
    	public boolean addRoom(int floor, Room r){
    		for(int i=0;i<floors.length;i++){
    				 if ((floors.equals(floor))&&
    				   (roomPerFloor1<maxRoomPerFloor))
    				   {
    				    floors[i].add(r);
    				   /*
    				    switch (floor) {
    		            case 1:  incroomPerFloor1();
    		                     break;
    		            case 2:  incroomPerFloor2();
                        		break;
    		            case 3:  incroomPerFloor3();
                        		break; 
    		            default: 
                        break;	
    				    }*/
    				}
     
    		}
    			incroomPerFloor1();
    		for(int i=0;i<floors.length;i++){
    			if ((floors.equals(floor))&&
    			   (getroomPerFloor2()<maxRoomPerFloor)){
    				floors[i].add(r);
    			}
    		}
     
    			incroomPerFloor2();
     
    		for(int i=0;i<floors.length;i++){
    			if ((floors.equals(floor))&&
    			   (roomPerFloor3<maxRoomPerFloor)){
    				floors[i].add(r);
    			}
    		}
    		    incroomPerFloor3();
     
    		if((roomPerFloor1>maxRoomPerFloor) || 
    		   (roomPerFloor2>maxRoomPerFloor) || 
    		   (roomPerFloor3>maxRoomPerFloor)){
    			System.out.println("full floor!!!");
    			return false;
    			}
    		return true;
     
    	}
     
    public static void main(String[]args)throws Exception{
    		Hotel hotel=new Hotel("Hilton","Brodway 1001");
    		//hotel.toString();
    		System.out.println("Hotel "+getName()+" is at address "+getAddress());
    		Room r=new Room(1,2,"view on beach");
    		System.out.println("room number: "+r.getRoomNumber()+" has number of beds: "
    		+r.getNumberOfBeds());
    		hotel.addRoom(0, r);
    		hotel.addRoom(0, r);
    		hotel.addRoom(0, r);
    		hotel.addRoom(0, r);
    		hotel.addRoom(0, r);
     
    		System.out.println("number of rooms on floor0: "+roomPerFloor1);
    		System.out.println("number of rooms on floor1: "+roomPerFloor2);
    		System.out.println("number of rooms on floor2: "+roomPerFloor3);
     
    	}
    }
    and the Room class so u can run it

    import java.util.ArrayList;
    import java.util.List;
     
    public class Room {
    	int roomNumber;
    	int numberOfBeds;
    	String description;
     
    	public Room(int num,int beds, String desc){
    		roomNumber=num;
    		numberOfBeds=beds;
    		description=desc;
    	}
    Question is the if statement if ((floors[i].equals(floor)) was giving me null pointer so i changed it with if ((floors.equals(floor)).
    The program is actually compiling and running but it seems somting is wrong he is adding rooms to every floor?
    Last edited by mihal; October 16th, 2012 at 03:29 PM.

Similar Threads

  1. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java SE API Tutorials
    Replies: 4
    Last Post: December 21st, 2011, 04:44 AM
  2. acessing variabloe outside loop
    By mhz041986 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 4th, 2011, 09:08 AM
  3. Ordering ArrayList by 3 conditions as you add to ArrayList
    By aussiemcgr in forum Collections and Generics
    Replies: 4
    Last Post: July 13th, 2010, 02:08 PM
  4. [SOLVED] Extracting an How to ArrayList from an ArrayList and convert to int??
    By igniteflow in forum Collections and Generics
    Replies: 2
    Last Post: August 16th, 2009, 01:11 PM
  5. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 1
    Last Post: May 17th, 2009, 01:12 PM