Category Archives: Homework

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: Writing Classes – Flowcharts

Assignment #1
Write the program for this flowchart, FlowchartProgram_YI.java

TwoCountersX

Assignment #2
Design your own flowchart (Make sure it makes sense!). Work with a partner to share your flowchart. In turn, your partner will share his/her flowchart with you. Both of you will write a program, MyPartnersFlowchart_YI.java for your partner’s flowchart.

It should not be too easy or too difficult.
The program should reflect the flowchart and you will be graded on how well you can implement your partner’s flowchart and how well your partner can implement your flowchart.
INCLUDE YOUR PARTNER’S NAME and the flowchart your partner drew.
NOTE: There are two posts for your work and your partner’s work.

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: Method Overloading

Method Overloading

  • Method overloading is useful when you need to perform similar operations on different types of data.
  • The same method name with different parameter list allows for method overloading.
  • The compiler must still be able to match up each invocation with a specific method declaration. If the method name for two or more methods is the same, then additional information is used to tell which version is being invoked.
  • In Java, a method name can be used for several methods as long as the number of parameters, the types of those parameters, and/or the order of the types of parameters is different.
  • A method’s name along with the number, type, and order of its parameters is called the method’s signature.
  • The compiler uses the complete method signature to bind a method invocation to its definition.

Class work:

1. Select a class of your choice and overload the constructor and a method. Submit also a test class to demonstrate the use of both constructors.

2. What error do you get if your overloaded constructor or method has the same signature as the original constructor or method? Based on the error given, can you deduce if overloading takes place at compilation or run time?

3. Write a method called evenlyDivisible that accepts two int parameters and returns true if the first parameter can be evenly divided by the second, or vice versa, and false if it can’t be. Return false if either parameter is zero. Overload evenlyDivisible to accept Integer parameters and have the same functionality. Include any comment you feel is appropriate.

4. Write a method called average that accepts two integer parameters and returns their average as a floating-point value. Overload the average method so that the method returns the average of three integers. Overload the average method to take four integer parameters and return their average.

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: 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

Chapter 3 – Test Review

Homework:

edmodo.com
Self-Review questions
Short Answers 3.17 through 3.19

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
https://www.cs.umd.edu/~clin/MoreJava/ControlFlow/dangling.html
Boolean expressions
Multiple Relational operators
Confusing && and || conditions
Lazy evaluation of Boolean operators

Chapter 3: Floating point Exercises

Find the errors in problems 1 through 8 and fix them if possible

1. if quarters > 0 then System.out.println(quarters + " quarters");
2. if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
3. if (x  =  1) y++;   else if  (x  =  2)   y  =  y  +  2;
4. if (x  && y  ==  0)   { x  =  1; y  = 1; }
5. if  (1 <=   X   <=  10) 
       System.out.println(x);
6. if (s !=  "nickels" || s  !=  "pennies"
      || s  !=  "dimes" || s  !=  "quarters")
      System.out.print("Input error!");
7. if (input.equalsIgnoreCase("N") || "NO")
      return;
8. int x  =  Integer.parseInt(input);
   if (x ! = null) y  =  y  +  x;
9. Write a truth table for the following boolean expressions and compare them: 

Complete the table below.
  p     q     r    (p && q) || !r     !(p && (q || !r))
  f     f     f
  f     f     t
  f     t     f
       ...
  5 more combinations

Programming Assignments:

1 . Write a program that reads in three floating-point numbers and prints the three inputs in sorted order. For example:

Please enter  three  numbers:
  4
  9
  2.5
The  inputs in sorted order are
  2.5
  4
  9

2. Write a Java program, CompareFloats_YI.java to show two floating-point numbers x and y such that Math.abs(x – y) is larger than 1000, but x and y are still identical except for a round­ off error.