go to previous page   go to home page   go to next page

Answer:

See Below


Completed Methods

Getters and setters would be easy if you could ignore errors. But you can't. There are various ways to deal with incorrect parameters. Exceptions would work nicely here, but that is a future topic.

In the code below, getTemp() returns 999 if dayNumber is out of range or the specified day does not have valid data. It is poor practice to have special numbers like this scattered throughout your code. Real-world programs can be hundreds of thousands of lines long and such "magic numbers" invite errors and confusion. See the next page.

setTemp() returns true if the operation succeeded, otherwise it returns false. This is a nice technique, but can't be used with the getter.


public class Month
{
  // instance variables
  private int   month;  // 1 == January
  private int   year;   // year as an int, eg 2017
  private int   daysInMonth;   // number of days in this month
  
  // temperature data
  private int[] temp;    // day 1 in temp[1] 
  private boolean[] valid;
  
  // constructors
  public Month( int month, int year)
  . . .
  
  // Getters and Setters
  public int getTemp( int dayNumber )
  {
    if ( dayNumber > 0 && dayNumber <= daysInMonth && valid[dayNumber] )
      return temp[ dayNumber ];
    else
      return 999;  // "magic" number, soon to be improved
  }

  public boolean setTemp( int dayNumber, int tmp )
  {
    if ( dayNumber > 0 && dayNumber <= daysInMonth )
    {
      temp[dayNumber] = tmp;
      valid[dayNumber] = true;
      return true;
    }
    else
      return false;
  }
}


QUESTION 7:

(Review: ) What does final mean in Java?


go to previous page   go to home page   go to next page