Source of UsingAnArray.java


  1: import java.util.Scanner;

  3: /**
  4:  * say how daily temps differed from a week's average
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class UsingAnArray {

 10:     /**
 11:      * Run this program.
 12:      *
 13:      * @param args command lines arguments (ignored)
 14:      */
 15:     public static void main(String[] args) {
 16:         // introduce self
 17:         System.out.println("\n"
 18:             + "This program reads in a week's worth of daily highs "
 19:             + "and prints out\nhow they differ from the average.\n");

 21:         // create variables
 22:         Scanner kbd = new Scanner(System.in);
 23:         double[] temps = new double[7];
 24:         double sum = 0.0;
 25:         double ave;

 27:         // read and sum the temperatures
 28:         System.out.println("Enter " + temps.length 
 29:             + " daily high temperatures below:");
 30:         for (int i = 0; i < temps.length; i++) {
 31:             temps[i] = kbd.nextDouble();    // read temp
 32:             sum += temps[i];            // add it to sum
 33:         }
 34:         kbd.nextLine();     // tidy up input stream

 36:         // calculate the average
 37:         ave = sum / temps.length;

 39:         // print the temps along with their difference from the average
 40:         System.out.print("\nDay\tHigh\tDifference");
 41:         System.out.print("\n---\t----\t----------\n");
 42:         for (int i = 0; i < temps.length; i++) {
 43:             System.out.println(i + "\t" + temps[i] + "\t" + (temps[i] - ave));
 44:         }
 45:         System.out.println();

 47:     }

 49: }