Farhan Aden
Farhan Aden

Reputation: 1

Adding Objects to an array in Java

I'm trying to have the user enter dates to store it but I can't seem to get it down.

public class Planner {
private int MaxEvents = 10;
private int numEvents=0;
OurDate a = new OurDate();
Event events []= new Event[MaxEvents];

public void enterDate(){
    OurDate date = new OurDate();
    Scanner input = new Scanner (System.in);
    System.out.print("Enter Date: \nEnter day: ");
    int day=input.nextInt();
    System.out.print("Enter month: ");
    int month=input.nextInt();
    System.out.print("Enter year: ");
    int year=input.nextInt();
    date.setDay(day);
    date.setMonth(month);
    date.setYear(year);
    events[numEvents] = date;
    numEvents++;

}

The problem comes when I try to add the created object to the array.

Here is the other class for reference for setDay,setMonth,setYear: public class OurDate { private int day; private int month; private int year;

public OurDate(int day, int month, int year){
    this.day = day;
    this.month = month;
    this.year = year;
}
public OurDate() {
    this.day=1;
    this.month = 1;
    this.year = 2010;
}
public void setDay(int day) {
    if(day>=1 && day <=31){
        this.day = day;
    }else if(day>31){
        this.day = 1;
    }
}
public int getDay() {
    return day;
}
public int getMonth() {
    return month;
}
public void setMonth(int month) {
    if(month >=1 && month<=12)
        this.month = month;
}
public int getYear() {
    return year;
}
public void setYear(int year) {
    this.year = year;
}


}

Upvotes: 0

Views: 3961

Answers (1)

Krasimir Stoev
Krasimir Stoev

Reputation: 1754

You cannot add an object of type OurDate to the array events because the array expects objects of type Event as mentioned in its declaration:

Event events []= new Event[MaxEvents];

Based on the code from your OurDate class, it does not extend Event, so adding such an object into the array cannot be done.

You can alter your array to take OurDate objects like that:

OurDate[] dates = new OurDate[MaxEvents];

Or you can create a new Event object and set the OurDate object in it - something like this:

Event event = new Event();
event.setDate(date);
events[numEvents] = event;

Upvotes: 2

Related Questions