By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,795 Members | 1,761 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,795 IT Pros & Developers. It's quick & easy.

non-static variable error ( simple )

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

Expand|Select|Wrap|Line Numbers
  1. public class Main {
  2.  
  3.     /**
  4.      * @param args the command line arguments
  5.      */
  6.     public static void main(String[] args) {
  7.  
  8.         Room[] rooms;
  9.         rooms = new Room[5];
  10.  
  11.         rooms[0] = new Room( 3, 7, true);
  12. /* non-static variable this cannot be referenced from a static context */
  13.  
  14.         for(int i = 1; i < 5; i++)
  15.         {
  16.             room[i] = new Room( 5, 5, true);
  17. /* non-static variable this cannot be referenced from a static context */
  18.         }
  19.         for(int i = 0; i < 5; i++)
  20.         {
  21.             room[i].printRoom();
  22. /* non-static variable this cannot be referenced from a static context */
  23.         }
  24.     }
  25.  
  26.     /* ****************************************** */
  27.  
  28.     class Room
  29.     {
  30.         int beds = 2; // 2 as defaukt number of beds
  31.         int guests = 0; // 0 as default number of guests
  32.         boolean smoking = false; // false as default for smoking
  33.  
  34.         Room(int beds, int guestss, boolean smoking)
  35.                 /*
  36.                  * A contructor for the Room class
  37.                  */
  38.         {
  39.             this.beds = beds;
  40.             guests = guestss;
  41.             this.smoking = smoking;
  42.         }
  43.  
  44.         public void printRoom()
  45.         {
  46.             System.out.println("Beds: " + beds + ". Guests: " +
  47.                     guests + ". Smoking: " + smoking);
  48.         }
  49.     }
  50.  
  51. }
/* 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
Mar 14 '09 #1
Share this Question
Share on Google+
1 Reply


Expert 10K+
P: 11,448
Your array is named 'rooms', not 'room', so you have rooms rooms[0], rooms[1] ... etc.

kind regards,

Jos
Mar 15 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.