CS 145 Lecture 15 – Arrays

Agenda

  • calculating a histogram
  • serializing data with arrays
  • turning a month number into a month name
  • turning a month/day into a day of the year

TODO

  • Read sections 7.1 and 7.2.

Program This

You are given a month and day, both as numbers. What day of the year is it? Write down your algorithm in pseudocode.

Code

Histogram.java

package preexam2;

import java.util.Scanner;

public class Histogram {
  public static void main(String[] args) {
    
    Scanner in = new Scanner(System.in);
//    int nZeroes = 0;
//    int nOnes = 0;
//    int nTwos = 0;
//    int nThrees = 0;
//    int nFours = 0;
//    int nFives = 0;
//    int nSixes = 0;
//    int nSevens = 0;
//    int nEights = 0;
//    int nNines = 0;
//    int nTens = 0;
    
    int[] counters = new int[7];
    
    System.out.print("# of kids in family: ");

    while (in.hasNextInt()) {
      int nSiblings = in.nextInt();
      counters[nSiblings]++;
      System.out.print("# of kids in family: ");

//      if (nSiblings == 0) {
//        nZeroes++;
//      } else if (nSiblings == 1) {
//        nOnes++;
//      } else if (nSiblings == 2) {
//        nTwos++;
//      } else if (nSiblings == 3) {
//        nThrees++;
//      } else if (nSiblings == 4) {
//        nFours++;
//      } else if (nSiblings == 5) {
//        nFives++;
//      } else if (nSiblings == 6) {
//        nSixes++;
//      } else if (nSiblings == 7) {
//        nSevens++;
//      }
    }
    
    for (int i = 0; i < counters.length; ++i) {
      System.out.println(i + ": " + counters[i]);
    }
  }
}

Date.java

package preexam2;

public class Date {
  public static void main(String[] args) {
    for (int i = 1; i <= 12; ++i) {
      System.out.println(monthNumberToName(i)); 
    }
  }
  
  public static String monthNumberToName(int i) {
    // make an array
    // first element is January
    // last element is December
    
    String[] monthNames = new String[12];
    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "Fooember";
    
    return monthNames[i - 1];
  }
}

Haiku

New is much like birth.
Arrays, fertility drugs.
You’ll number those kids.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *