non-static variable error ( simple )

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JavaJon
    New Member
    • Mar 2009
    • 2

    #1

    non-static variable error ( simple )

    The problem in the follow code occurs when trying to instantiate an array object.

    Code:
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
            Room[] rooms;
            rooms = new Room[5];
    
            rooms[0] = new Room( 3, 7, true);
    /* non-static variable this cannot be referenced from a static context */
    
            for(int i = 1; i < 5; i++)
            {
                room[i] = new Room( 5, 5, true);
    /* non-static variable this cannot be referenced from a static context */
            }
            for(int i = 0; i < 5; i++)
            {
                room[i].printRoom();
    /* non-static variable this cannot be referenced from a static context */
            }
        }
    
        /* ****************************************** */
    
        class Room
        {
            int beds = 2; // 2 as defaukt number of beds
            int guests = 0; // 0 as default number of guests
            boolean smoking = false; // false as default for smoking
    
            Room(int beds, int guestss, boolean smoking)
                    /*
                     * A contructor for the Room class
                     */
            {
                this.beds = beds;
                guests = guestss;
                this.smoking = smoking;
            }
    
            public void printRoom()
            {
                System.out.println("Beds: " + beds + ". Guests: " +
                        guests + ". Smoking: " + smoking);
            }
        }
    
    }
    /* non-static variable this cannot be referenced from a static context */
    Why does this happen? In other words, could someone explain in brief what's happening - And how to fix it.

    Thanks in advance,

    Jon
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Your array is named 'rooms', not 'room', so you have rooms rooms[0], rooms[1] ... etc.

    kind regards,

    Jos

    Comment

    Working...