Category Archives: Class work

Chapter 4: Lessons Questions Part 3

Classwork/Homework:
Answer the following questions:

  1. What does the author mean by “Objects should be self-governing”?

  2. What is the “public interface” to an object?

  3. Why might a constant be given public visibility?

  4. Why is a method invoked through (or on) a particular object? What is the exception to that rule?

  5. In the Banking program:
    a. How many Account objects are created?
    b. How many arguments (actual parameters) are passed to the
    withdraw method when it is invoked on the acct2 object?
    c. How many arguments (actual parameters) are passed to the
    addInterest method when it is invoked on the acct3 object?

  6. Which of the Account class methods would you classify as accessor
    methods? As mutator methods? As service methods?

Read up to page 225

Chapter 4: Tracing 101-2

Classwork:

Use paper and pencil/pen to trace this code snippets and show how each of the choices fail except one:

Lazy student spoiler: DO NOT USE THE COMPUTER

a.
One of the rules for converting English to Pig Latin states: If a word begins with a
consonant, move the consonant to the end of the word and add “ay”. Thus “dog”
becomes “ogday”, and “crisp” becomes “rispcay”. Suppose s is a String
containing an English word that begins with a consonant. Which of the following
creates the correct corresponding word in Pig Latin? Assume the declarations

String ayString =”ay”;
String pigString;
pigString = s.substring(0,s.length()) + s.substring(0,1) + ayString;
pigString = s.substring(1,s.length()) + s.substring(0,0) + ayString;
pigString = s.substring(0,s.length()-1) + s.substring(0,1) + ayString;
pigString = s.substring(1,s.length()-1) + s.substring(0,0) + ayString;
pigString = s.substring(1,s.length()) + s.substring(0,1) + ayString; 

b.
This question refers to the getString method shown below:

public static String getString(String s1, String s2)
{
    int index = s1.indexOf(s2); // it returns the index of s2
    return s1.subtring(index, index + s2.length());
}

Which is true about getString? It may return a string that
I Is equal to s2.
II Has no characters in common with s2.
III Is equal to s1.

c.

public static String doSomething(String s)
{
    Final String BLANK = " ";            //BLANK contains a single space
    String str = "";                     // empty String
    String temp;
    for (int i = 0; i < s.length(); i++)
    {
        temp =s.substring(i, i + 1);
        if ( !(temp.equals(BLANK)))
             str += temp;
    }
    return str;
}

Shows how each doesn’t work except the right one:
It returns s unchanged.
It returns s with all its blanks removed.
It returns a String that is equivalent to s with all its blanks removed.
It returns a String that is an exact copy of s.
It returns a String that contains s.length() of blanks.

NOTE: Do the work even if you got the questions right.

Ch2TestSolTracing.pdf
Printer-friendly version

I will collect your work at the end of the period.

Chapter 4: Die ADT

Chapter 4 – Writing Classes
Back to topics from the previous lesson.

  1. Describe the instance data of the Die class.
  2. Which of the methods defined for the Die class can change the state of a Die object-that is, which of the methods assign values to the instance data?
  3. What happens when you pass an object to a print or println method?
  4. What is the scope of a variable?
  5. What are UML diagrams designed to do?

Programming Projects::

PP 4.3 Write an application (driver) that rolls a die and displays the result. Let the user pick the number of sides on the die. Use the Die class from this chapter to represent the die in your program.
Include a UML class diagram.

UML Basics

PP 4.4 Design and implement a class called PairOfDice_YI, with two six-sided Die objects. Create a driver class called BoxCars_YI with the main method that rolls a PairOfDice_YI object 1000 times, counting the number of boxcars (two sixes) that occur. Print a full sentence with the outcome. Run the driver/test class at least 3 times.
Include a UML class diagram.

PP 4.5 Using the PairOfDice_YI class from Programming Project 4.4, design and implement a class to play a game called Pig_YI. In this game, the user competes against the computer. On each turn, the player rolls a pair of dice and adds up his or her points. Whoever reaches 100 points first, wins. If a player rolls a 1, he or she loses all points for that round and the dice go to the other player. If a player rolls two 1s in one turn, the player loses all points earned so far in the game and loses control of the dice. The player may voluntarily turn over the dice after each roll. So the player must decide to either roll again (be a pig) and risk losing points, or give up the dice, possibly letting the other player win. Set up the computer player so that it always gives up the dice after getting 20 or more points in a round.
Draw a flowchart.

Flowcharts: Most used shapes and Examples

Use draw.io or google draw for the flowchart.
Screen Shot 2014-09-28 at 3.36.01 PM

Die.java

//********************************************************************
//  Die.java       Author: Lewis/Loftus/Cocking
//
//  Represents one die (singular of dice) with faces showing values
//  between 1 and the number of faces on the die.
//********************************************************************

import java.util.Random;
public class Die
{
   private final int MIN_FACES = 4;

   private static Random generator = new Random();
   private int numFaces;   // number of sides on the die
   private int faceValue;  // current value showing on the die

   //-----------------------------------------------------------------
   //  Defaults to a six-sided die. Initial face value is 1.
   //-----------------------------------------------------------------
   public Die ()
   {
      numFaces = 6;
      faceValue = 1;
   }

   //-----------------------------------------------------------------
   //  Explicitly sets the size of the die. Defaults to a size of
   //  six if the parameter is invalid.  Initial face value is 1. 
   //-----------------------------------------------------------------
   public Die (int faces)
   {
      if (faces < MIN_FACES)
         numFaces = 6;
      else
         numFaces = faces;

      faceValue = 1;
   }

   //-----------------------------------------------------------------
   //  Rolls the die and returns the result.
   //-----------------------------------------------------------------
   public int roll ()
   {
      faceValue = generator.nextInt(numFaces) + 1;
      return faceValue;
   }

   //-----------------------------------------------------------------
   //  Returns the current die value.
   //-----------------------------------------------------------------
   public int getFaceValue ()
   {
      return faceValue;
   }
}

[collapse]

Chapter 4: Short Answers

4.1 Write a method header for a method named translate that takes an integer parameter and returns a double.

4.2 Write a method header for a method named find that takes a String and a double as parameters and returns an integer.

4.3 Write a method header for a method named printAnswer that takes three doubles as parameters and doesn’t return anything.

4.4 Write the body of the method for the following header. The method should return a welcome message that includes the user’s name and visitor number. For example, if the parameters were “Joe” and 5, the returned string would be “Welcome Joe! You are visitor number 5.” String welcomeMessage (String name, int visitorNum)

4.5 Write a method called powersOfTwo that prints the first 10 powers of 2 (starting with 2). The method takes no parameters and doesn’t return anything.

4.6 Write a method called alarm that prints the string”Alarm! ” several times on separate lines. The method should accept an integer parameter that tells it how many times the string is printed. Print an error message if the parameter is less than 1.

4.7 Write a method called sum100 that adds up all the numbers from 1 to 100, inclusive and returns the answer.

4.8 Write a method called maxOfTwo that accepts two integer parameters from the user and returns the larger of the two.

4.9 Write a method called sumRange that accepts two integer parameters that represent a range such as 50 to 75. Issue an error message and return zero if the second parameter is less than the first. Otherwise, the method should return the sum of the integers in that range (inclusive).

4.11 Write a method called countA that accepts a String parameter and returns the number of times the character ‘A’ is found in the string.

4.13 Write a method called average that accepts two integer parameters and returns their average as a floating-point value.

4.14 Overload the average method of Exercise 4.13 so that the method returns the average of three integers.

4.15 Overload the average method of Exercise 4.13 to take four integer parameters and return their average.

4.16 Write a method called multiConcat that takes a String and an integer as parameters. Return a String made up of the string parameter concatenated with itself count times, where count is the integer.
For example, if the parameter values are “hi” and 4, the return value is “hihihihi”.Return the original string if the integer parameter is less than 2.

4.17 Overload the multiConcat method from Exercise 4.16 so that if the integer parameter is not provided, the method returns the string concatenated with itself. For example, if the parameter is
“test”, the return value is “testtest”.

4.19 Write a method called floatEquals that accepts three floating-point values as parameters. The method should return true if the first two parameters are no further apart from each other than the third parameter.
For example, floatEquals (2.453, 2.459, 0.01) should return true because 2.453 and 2.459 are 0.006 apart from each other and 0.006 is less than 0.01.
Hint: recall the discussion on comparing floating-point values for equality.

Chapter 3: Comparing Floating Point Numbers

Chapter 4: Changes to Student ADT

Programming Assignment 4.8
Change the Student class so that each student object also contains the scores for three tests.
a. Provide a constructor that sets all instance values based on parameter values.

b. Overload the constructor so that each test score starts out at zero.

c. Provide a method called setTestScore that accepts two parameters: the test number (1 through 3) and the score.

d. Also provide a method called getTestScore that accepts the test number and returns the score.

e. Provide a method called average that computes and returns the average test score for this student.

f. Modify the toString method so that the test scores and average are included in the description of the student.

g. Modify the driver class main method to exercise the new Student methods.

h. Add to your test class a feature to calculate the highest and lowest average grades of at least 5 students.

testscores

//********************************************************************
//  Student.java       Author: Lewis/Loftus/Cocking
//
//  Represents a college student.
//********************************************************************

public class Student
{
   private String firstName, lastName;
   private Address homeAddress, schoolAddress;
  
   //-----------------------------------------------------------------
   //  Sets up this Student object with the specified initial values.
   //-----------------------------------------------------------------
   public Student (String first, String last, Address home,
                   Address school)
   {
      firstName = first;
      lastName = last;
      homeAddress = home;
      schoolAddress = school;
   }

   //-----------------------------------------------------------------
   //  Returns this Student object as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      String result;

      result = firstName + " " + lastName + "\n";
      result += "Home Address:\n" + homeAddress + "\n";
      result += "School Address:\n" + schoolAddress;

      return result;
   }
}

Chapter 3 – Slot Machine

September 24th, 2015

Classwork/Homework
Design and implement an application, YI_SloptMachine.java that simulates a simple slot machine in which three numbers between 0 and 9 are randomly selected and printed side by side. Print a statement saying all three of the numbers are the same, or any two of the numbers are the same, when this happens. Keep playing until the user chooses to stop.
Screen Shot 2014-09-16 at 2.47.15 PM

Homework:
Short answer 3.6 through 3.10.

Chapter 3: Std Lib – Graphics Review

Classwork:

3.17 Design and implement an application that draws the side view of stair steps from the lower left to the upper right.

3.18 Design and implement an application that draws 100 circles of random color and random diameter in random locations. Make sure that in each case the whole circle appears in the visible area.

You can use the libraries from PU:
Screen Shot 2015-09-10 at 9.16.47 AM

 
Homework:
Short Answers 3.12 through 3.17
T/F 1 through 9

 
Chapter 3 Test Review
Review from the book the following material:
The “if” statement
Block Statement
Selection operator: ternary if
Brace layout
Indentation and tabs
Conditions with side effects
The “switch” statement
The “dangling” else
Boolean expressions
Multiple Relational operators
Confusing && and || conditions
Lazy evaluation of Boolean operators

Chapter 3 – Rock-paper-scissors

Classwork:
Homework review

Classwork/Homework
Design and implement an application that plays the rock-paper-scissors game against the computer. When played between two people, each person picks one of three options (usually shown by a hand gesture) at the same time, and a winner is determined. In the game, rock beats scissors, scissors beats paper, and paper beats rock. The program should randomly choose one of the three options (without revealing it), then ask for the user’s selection. At that point, the program reveals both choices and prints a statement indicating that the user won, that the computer won, or that it was a tie. Keep playing until the user chooses to stop, then print the number of user wins, losses, and ties.

rockpaperscissor

screen-shot-2016-09-20-at-6-46-04-pm