jeudi 17 septembre 2020

Is there an easy way to use a toString() method in two different classes?

So this program uses 3 different classes, "Year", "Decade", and a tester. To start off, the "Year" class is supposed to create 2 attributes: yearNum, which holds the year number, i.e. 1917, and, monthList, which is an ArrayList of months. Here's what I have:

import java.util.ArrayList;
public class Year {

  private int numYear;
  private ArrayList<String> monthList;

  public Year() {
    numYear = 0;
    monthList.add("January");
    monthList.add("February");
    monthList.add("March");
    monthList.add("April");
    monthList.add("May");
    monthList.add("June");
    monthList.add("July");
    monthList.add("August");
    monthList.add("September");
    monthList.add("October");
    monthList.add("November");
    monthList.add("December");
  }
  public Year(int numYear, ArrayList<String> monthList) {
    this.numYear = numYear;
    this.monthList = monthList;
  }
  public int getNumYear() {
    return numYear;
  }
  public ArrayList<String> getMonthList() {
    return monthList;
  }
  public void setNumYear(int numYear) {
    numYear = this.numYear;
  }
  public String toString() {
    return "" + numYear;
  }
}

Then the "Decade" is supposed to create an array of 10 "Year" objects. What I have so far:

public class Decade {

  int[] arrayYear1 = new int[1];
  int[] arrayYear2 = new int[1];
  int[] arrayYear3 = new int[1];
  int[] arrayYear4 = new int[1];
  int[] arrayYear5 = new int[1];
  int[] arrayYear6 = new int[1];
  int[] arrayYear7 = new int[1];
  int[] arrayYear8 = new int[1];
  int[] arrayYear9 = new int[1];
  int[] arrayYear10 = new int[1];

}

Finally, the tester, creates a random Decade object, by choosing a random number between 1900 and 1999 for a year number. Then it finds the starting year for that random number to create a Decade object which, includes the random year number. For example, if the random number is 1993, the program creates a Decade object for 1990 decade.

The tester then calls the Decade's toString method to display (that uses Year class's toString method) the months of that year in this format:

>January 1993
February 1993<

I'm stuck and don't really know how to go from here. Starting with finishing the "Decade" class and using the toString() method.




Aucun commentaire:

Enregistrer un commentaire