Jump to content

  • Log In with Google      Sign In   
  • Create Account


Arrays of class objects in Java


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 Keyeszx   Members   -  Reputation: 144

Like
0Likes
Like

Posted 01 March 2014 - 06:27 AM

For a class assignment we've been tasked with making an appointment class that holds some variables and another class that makes an array of the appointment class. But I'm not sure if I'm adding the appointment object correctly.

    public class Appointment {
     
        private int date, hour, minute;
        private String month, msg;
     
        public Appointment() {
            setMonth("APR");
            setDate(4);
            setHour(0);
            setMinute(0);
            setMessage("Default Message");
        }
    //constructor that takes parameters
    //main method that creates two objects to test the constructors, will be deleted before finished
    //set and get methods
    //toString method to print the values the object's variable values
    }
     
     
    public class Planner {
    Appointment[] DayPlanner = new Appointment[20];
    DayPlanner[0] = new Appointment();              //Error: ']' expected | invalid method declaration; return type required
       
    }



Edited by Keyeszx, 01 March 2014 - 06:29 AM.


Sponsor:

#2 dr01d3k4   Members   -  Reputation: 402

Like
0Likes
Like

Posted 01 March 2014 - 07:17 AM

You can't put code that actually does something like "DayPlanner[0] = new Appointment();" in just the class body. It has to be either in a method or a static block, though that would require DayPlanner to be a static member of Planner.

 

I'd change it to look like this:

public class Planner {
	private Appointment[] dayPlanner;



	public Planner(int maxAppointments) {
		dayPlanner = new Appointment[maxAppointments];
		dayPlanner[0] = new Appointment();
	}
}



// Create a planner with 20 appointments
new Planner(20);

However I would recommend using an ArrayList<Appointment> instead of a fixed array.


Falling block colour flood game thing I'm making: http://jsfiddle/dr01d3k4/JHnCV/


#3 de_mattT   Members   -  Reputation: 308

Like
0Likes
Like

Posted 01 March 2014 - 09:27 AM

Or an alternative would be to create the instances of Appointment when you create DayPlanner, e.g.

public class Planner {
    Appointment[] DayPlanner = new Appointment[] {new Appointment(), new Appointment(), new Appointment()};
}

DayPlanner is an array with 3 elements.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS