Homework 2

  1. Ch 2 Exercises 2:

One way.

package calendar;

 

public class MyDate {

 

      // number of days in each month

      private static  int[] days_in_month = {31, 28, 31, 30, 31, 30,

                                               31, 31, 30, 31, 30, 31};

      private static int GREGORIAN_YEAR = 1582;

      private static int MAX_MONTH = 11;

      private static int FEB_DAYS = 28;

 

      // internal representation of date

      private int year; // >= 1582, year Gregorian calendar invented

      private int month; // 0-11

      private int day; // 1 - last day of month

 

      /** Constructs a MyDate object.

         *  pre: year >= 1582, month 1-12, day 1 to last day of month

         *       Feb has 28 days, except in leap years when it has 29 days.

         *       Years evenly divisible by 4 are leap years except century years.

         *       A century year divisible by 4 is a leap year, other

         *       century years are not leap years.

         *  post: a MyDate object is constructed

       *        a RuntimeException is thrown for invalid input

      */

      public MyDate(int year, int month, int day) {

                  if (!isLegal(year, month-1, day)) {

                              throw new RuntimeException("Invalid date");

                  }

                  this.year = year;

                  this.month = month-1;

                  this.day = day;

      }

 

      /** Creates a new MyDate object one day later than the input.

          * pre: a valid MyDate object is passed as a parameter

        * post: a new valid MyDate object is constructed that is one day later

      */

      public static MyDate addDay(MyDate date) {

                  int new_year = date.year;

                  int new_month = date.month;

                  int new_day = date.day + 1;

                  if (!isLegal(new_year, new_month, new_day)) {

                              new_day = 1;

                              new_month++;

                              if (!isLegal(new_year, new_month, new_day)) {

                                          new_month = 0;

                                          new_year++;

                              }

                  }

                  return new MyDate(new_year, new_month+1, new_day);

      }

 

      // returns true if parameters correspond to a valid date

        // with year >= 1582, false otherwise

      private static boolean isLegal(int year, int month, int day) {

                  if (year < GREGORIAN_YEAR) {

                              return false;

                  } else if (day < 1) {

                              return false;

                  } else if (month < 0 || month > MAX_MONTH) {

                              return false;

                  } else if (month != 1 && day > days_in_month[month]) {

                              return false;

                  } else if (month == 1) {

                              if (isLeapYear(year) && day > FEB_DAYS + 1) {

                                          return false;

                              } else if (!isLeapYear(year) & day > FEB_DAYS) {

                                          return false;

                              }

                  }

                  return true;

      }

 

      // return true if a year is a leap year, false otherwise

      private static boolean isLeapYear(int year) {

                  // if year is a century year

                  if (year % 100 == 0) {

                              // if century evenly divisible by 4

                              if ( (year / 100) % 4 == 0) {

                                          return true;

                              } else {

                                          return false;

                              }

                  } else  {

                              // if year evenly divisible by 4, then return true

                              // else return false

                              return (year % 4) == 0;

                  }

      }

 

      /** Returns a String representation of a date formatted as mm/dd/yy

          * pre: N/A

        * post: returns a String representation of date as mm/dd/yyyy

       */

      public String toString() {

                  // note conversion from 0 based internal representation of

                  // to 1 base presentation

                  return String.format("%d/%d/%d", month+1, day, year);

      }

}

 

Another way. Note, code reuse is good!!! It’s a major reason for OOP.

/*

     *PURPOSE: Adds a day to a given date

     *PARAMETERS: A GregorianCalendar object

     *PRE: Parameter date is a valid date

     *POST: Parameter date is a valid date one day later

    */

    public static void addDay(GregorianCalendar date) {

        // See java API for use of GregorianCalendar class

        date.add(Calendar.DAY_OF_MONTH, 1);

    }

   

  1. Ch 2 Exercise 3:

    // PURPOSE: Display prompt and read user input from stdin.

    //          Return user input as an int. Quit if user enters

    //          quit in any case. Prompt user again if input not

    //          an integer.

    // PRE:     stdin is a valid BufferedReader

    // POST:    Returns an int or terminates program

    static int getInt(String prompt, BufferedReader stdin) {

        boolean okay = false;

        int value = 0;

        String in = "";

        do {

            System.out.println(prompt);

            try {

                in = stdin.readLine();

                value = Integer.parseInt(in);

                okay = true;

            } catch (IOException e) {

                e.printStackTrace();

                System.exit(1);

            } catch (NumberFormatException e){

                if (in.equalsIgnoreCase("quit")) {

                    System.out.println("Ending input");

                    System.exit(0);

                }

                System.out.println

                        ("You must enter a number or quit, please try again");

            }

        } while (!okay);

        return value;

    }

   

    // PURPOSE: Read user input of id, age, salary and name; quit when

    //          user types quit in any case.

    // PRE:     N/A

    // POST:    User input is displayed to the screen.

    public static void Exercise3() {

        /*

         *Problems with book code:

         *  1) User is not prompted

         *  2) User must enter the next id, age and salary before quitting

         *  3) No exception handling or friendly error messages

         *  4) User input not echoed back to the screen

        */

        BufferedReader stdin = new BufferedReader(

            new InputStreamReader(System.in));

        System.out.println("Please enter requested information.");

        System.out.println("Enter quit at any time to end input.");

        int count = 0;

        do {

            try {

                System.out.println("Person " + (++count));

                int id = getInt("Id (e.g., 1234):", stdin);

                int age = getInt("Age (e.g., 33): ", stdin);

                int salary =

                        getInt("Salary (thousands of dollars): ", stdin);

                System.out.println("Name: ");

                String name = stdin.readLine();

                System.out.printf

                        ("Entry Id: %d\tAge: %d\tSalary: %d\tName: %s",

                            id, age, salary, name);

            } catch (IOException e) {

                e.printStackTrace();

                System.exit(1);

            }

        }while (count < 10);

    }

  1. Ch 2 Exercise 6:

    // PURPOSE: Calculate the square root of a double divided by

    //          cos of the double

    // PRE:     0 <= x < Math.PI / 2.0;

    // POST:    returns sqrt(x)/cos(x)

    //  Note:   Result can be Math.NaN or Math.POSITIVE_INFINITY or

    //          Math.NEGATIVE_INFINITY, depending on x

    public static double computation(double x) {

        return java.lang.Math.sqrt(x)/java.lang.Math.cos(x);

    }

    public static void Exercise6() {

        double x = computation(-10.0);

        // Here is how to check for Not a Number (NaN) or Infinity.

        if (Double.isNaN(x) || Double.isInfinite(x)) {

            System.out.println ("Invalid input");

        } else {

            System.out.println("x = " + x);

        }

       

    }

  1. Ch 2 Exercise 13:

a.      7

b.      Change

while (temp1 < x) {

                                    to

                                                while (temp1 <= x) {

                                    Notes: 1) Sum of consecutive odd numbers starting with 1 is a perfect square. Hence temp1 is a perfect square.

                                                2) Code should look for result2 <= x < (result + 1)2. In fact it was looking for result2 < x <= (result + 1)2

                                                3) Problem only occurred when x was a perfect square.

c. Program should 1) prompt user; and 2) check that the user input is a non-negative int and reprompt user if it isn’t.

  1. Suppose you have a sub-directory in your home directory called game and inside this directory you have a file called checkers.class containing a class called checkers (with a main method) in the package game. Your current directory is not your home directory. What command(s) can you execute to run checkers.class?

You have to make the assumption that your application does not import anything not already known to the java application. With this assumption, the following will work

java –classpath ~ game.checkers