Faizan Haque
Faizan Haque

Reputation: 17

(Java) An Array of a class

I have a class here which gives me back a date in a certain order what i want to do is make an array of this class with four type of Dates.

How can I fit these dates in the Array ????

public class DateArray {

  private String month; 
  private int day; 
  private int year; 


  public DateArray(String n, int d, int y){
    month = n;
    day = d;
    year = y;
  }


  public String toString(){
    return month + "/" + day + "/" + year; 
  }

This is what my Main looks like right now:

DateArray date = new DateArray("jan", 5, 20);
String s =  date.toString();

System.out.println(s);

DateArray [] dates = new DateArray[3];


for(int i =0; i<dates.length; i++)
{
    System.out.println(dates[i]);
}

Upvotes: 0

Views: 49

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201487

First, based on your expected results, your DateArray.toString() should look something like1

@Override
public String toString() {
    return month + " " + day + ", " + year;
}

Then you can create and display your array with something like

public static void main(String[] args) {
    DateArray[] dates = new DateArray[] { new DateArray("May", 16, 1984), 
            new DateArray("November", 14, 1978),
            new DateArray("September", 21, 1980), new DateArray("July", 3, 1987) };
    for (DateArray da : dates) {
        System.out.println(da);
    }
}

And I get (as requested)

May 16, 1984
November 14, 1978
September 21, 1980
July 3, 1987

1The Override annotation can help you if you think you're correctly overriding a super-type method but you aren't. I suggest you always use it.

Upvotes: 1

Lew Bloch
Lew Bloch

Reputation: 3433

You haven't set any values for the array elements in your code example. You need something similar to

dates[0] = new DateArray(month, day, year);

for each element. Also, I suggest that naming a type 'Array' that isn't an array might be confusing.

Upvotes: 1

Related Questions