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

Answer:

final is used for named constants.


Slight Improvement

In the slightly improved code, ERRORFLAG is used as a return value to flag an error. The caller is expected to check the return value before using it. In a large project, the same value could be used throughout the code. This improves readability and consistency. If the value needs to change (global warming?) the change can be made in just one place.


public class Month
{
  // constants
  final int ERRORFLAG = 999;
  
  // 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; 
  ... 
  
  // Getters and Setters
  public int getTemp( int dayNumber )
  {
    if ( dayNumber > 0 && dayNumber <= daysInMonth && valid[dayNumber] )
      return temp[ dayNumber ];
    else
      return ERRORFLAG;  
  }

  public int getTemp( int dayNumber )
  {
    if ( dayNumber > 0 && dayNumber <= daysInMonth && valid[dayNumber] )
      return temp[ dayNumber ];
    else
      return ERRORFLAG;  
  }
 
  ... 
   
  public String toString()
  {
    String str = month + "/" + year + "\n";
    
    for ( int day = 1;   ; day++ )
    {
      str += day + ": ";
      if (  ) 
        str += temp[day] ;
      else
        str += "no data";
      str += "\n";
    }
    return str;
  }    
  }
}

Amusing story: as the year 2000 was approaching, many programs needed to be fixed because they used two digits for the year. "65" was used for "1965" and so on. Uninitialized years were set to "99" which, when the programs were written, was far into the future. But in "1999" this value did not work. Many VHR recorders stopped working in 1999.


QUESTION 8:

Of course, we need a toString() method. Please complete it.


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