CS 1401 Assignment #10, Solutions

Date Assigned: Monday, April 2, or Tuesday, April 3, 2007.

Due Date: Monday, April 9, or Tuesday, April 10, 2007, before the beginning of your lab section.

Objective: The main objective of this assignment is to learn to use arrays of objects.

Programming assignment: The task is the same as in the previous Assignment 9: Write a program for analyzing El Paso weather. This program must allow the user to enter dates followed by temperatures at these dates. Assume that we are only tracing one year, so the overall number of such dates does not exceed 366. Your must then output the following information:

Main difference: In the previous assignment 9, following our advise, you stored the dates in one array (array of strings), and temperatures in another array (array of numbers).

For this new assignment, define a class Record whose objects contain two fields:

Instead of using two arrays, use a single array of records (i.e., of objects of type Record).

Deliverables: as instructed by your TA.


import java.util.*;

public class Record{
  private String date;
  private int temperature;

  public Record(String adate, int atemperature){
    date = adate; temperature = atemperature;}

  public String getDate(){return date;}
  public int getTemperature(){return temperature;}

  public void setDate(String newDate){date = newDate;}
  public void setTemperature(int newTemperature)
    {temperature = newTemperature;}

public static void main(String[] args){
  Record[] records = new Record[366];
  Scanner reader = new Scanner(System.in);
  String day;
  int temp;
  int numberOfDates = 0;
  boolean done = false;
  char yesNo;
  int i = 0;

  //reading the data
  while (!done)
    System.out.print("Do you want to input more data? Y/N");
    yesNo = reader.next().charAt(0);
    if (yesNo == 'Y')
      System.out.println("Enter the date");
      day = reader.next();
      System.out.println("Enter the temperature");
      temp = reader.nextInt();
      records[i] = new Record(day, temp);
      {done = true;}

  //computing the average
  double sum = 0.0;
  for (i = 0; i < numberOfDates; i++)
    {sum += records[i].getTemperature();}
  double average = sum / numberOfDates;
  System.out.println("The average temperature in El Paso is " + average);

  //printing all the days when the temperature was below freezing
  System.out.println("Days when temperature was below freezing:");
  for (i = 0; i < numberOfDates; i++)
    {if (records[i].getTemperature() < 32)

  //computing the hottest temperature
  int hottestSoFar = records[0].getTemperature();
  for (i = 1; i < numberOfDates; i++)
    {temp = records[i].getTemperature();
    if (temp > hottestSoFar) {hottestSoFar = temp;}}

  //printing all the days when the temperature was the hottest
  System.out.println("Days when temperature was the hottest:");
  for (i = 0; i < numberOfDates; i++)
    {if (records[i].getTemperature() == hottestSoFar)