Category Archives: Lesson

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: Method decomposition – Static Variables & methods

From Java Software Solutions by Lewis, Loftus, and Cocking
Static Keyword youtube Video

Static Keyword Video

Assignments:
1. Explain why a static method cannot refer to an instance variable.
2. Can a static method be referenced with the “this” operator? Explain
3. What is the purpose of static variables since a static variable belongs to the class, not to an object?
4. How are static variables and methods used?
5. Modify the PigLatinTranslator class so that its translate method is static. Modify the PigLatin class so that it invokes the method correctly.

Method decomposition

Sometimes it is useful to decompose a method into multiple methods to create a more understandable design. As an example, let’s examine a program that translates English sentences into Pig Latin.

Pig Latin is a made-up language in which each word of a sentence
is modified, in general, by moving the initial sound of the word to the end and adding an “ay” sound. For example, the word happy would be written and pronounced appyhay and the word birthday would become irthdaybay. Words that begin with vowels simply have a “yay” sound added on the end, turning the word enough into enoughyay. Consonant blends such as “ch” and “st” at the beginning of a word are moved to the end together before adding the “ay” sound. Therefore the word grapefruit becomes apefruitgray.

The real workhorse behind the PigLatin program is the PigLatinTranslator class. An object of type PigLatinTranslator provides a method called translate, which accepts a string and translates it into Pig Latin. Note that the PigLatinTranslator class does not contain a constructor because none is needed.

//********************************************************************
//  PigLatin.java       Author: Lewis/Loftus
//
//  Demonstrates the concept of method decomposition.
//********************************************************************

import java.util.Scanner;

public class PigLatin
{
   //-----------------------------------------------------------------
   //  Reads sentences and translates them into Pig Latin. 
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      String sentence, result, another;
      PigLatinTranslator translator = new PigLatinTranslator();
      Scanner scan = new Scanner (System.in);

      do
      {
         System.out.println ();
         System.out.println ("Enter a sentence (no punctuation):");
         sentence = scan.nextLine();

         System.out.println ();

         result = translator.translate (sentence);
         System.out.println ("That sentence in Pig Latin is:");
         System.out.println (result);

         System.out.println ();
         System.out.print ("Translate another sentence (y/n)? ");
         another = scan.nextLine();
      }
      while (another.equalsIgnoreCase("y"));
   }
}


 

//********************************************************************
//  PigLatinTranslator.java       Author: Lewis/Loftus
//
//  Represents a translator from English to Pig Latin. Demonstrates
//  method decomposition.
//********************************************************************

import java.util.Scanner;

public class PigLatinTranslator
{
   //-----------------------------------------------------------------
   //  Translates a sentence of words into Pig Latin.
   //-----------------------------------------------------------------
   public String translate (String sentence)
   {
      String result = "";

      sentence = sentence.toLowerCase();

      Scanner scan = new Scanner (sentence);

      while (scan.hasNext())
      {
         result += translateWord (scan.next());
         result += " ";
      }

      return result;
   }

   //-----------------------------------------------------------------
   //  Translates one word into Pig Latin. If the word begins with a
   //  vowel, the suffix "yay" is appended to the word.  Otherwise,
   //  the first letter or two are moved to the end of the word,
   //  and "ay" is appended.
   //-----------------------------------------------------------------
   private String translateWord (String word)
   {
      String result = "";

      if (beginsWithVowel(word))
         result = word + "yay";
      else
         if (beginsWithBlend(word))
            result = word.substring(2) + word.substring(0,2) + "ay";
         else
            result = word.substring(1) + word.charAt(0) + "ay";

      return result;
   }

   //-----------------------------------------------------------------
   //  Determines if the specified word begins with a vowel.
   //-----------------------------------------------------------------
   private boolean beginsWithVowel (String word)
   {
      String vowels = "aeiou";

      char letter = word.charAt(0);

      return (vowels.indexOf(letter) != -1);
   }

   //-----------------------------------------------------------------
   //  Determines if the specified word begins with a particular
   //  two-character consonant blend.
   //-----------------------------------------------------------------
   private boolean beginsWithBlend (String word)
   {
      return ( word.startsWith ("bl") || word.startsWith ("sc") ||
               word.startsWith ("br") || word.startsWith ("sh") ||
               word.startsWith ("ch") || word.startsWith ("sk") ||
               word.startsWith ("cl") || word.startsWith ("sl") ||
               word.startsWith ("cr") || word.startsWith ("sn") ||
               word.startsWith ("dr") || word.startsWith ("sm") ||
               word.startsWith ("dw") || word.startsWith ("sp") ||
               word.startsWith ("fl") || word.startsWith ("sq") ||
               word.startsWith ("fr") || word.startsWith ("st") ||
               word.startsWith ("gl") || word.startsWith ("sw") ||
               word.startsWith ("gr") || word.startsWith ("th") ||
               word.startsWith ("kl") || word.startsWith ("tr") ||
               word.startsWith ("ph") || word.startsWith ("tw") ||
               word.startsWith ("pl") || word.startsWith ("wh") ||
               word.startsWith ("pr") || word.startsWith ("wr") ); 
   }
}


 

The act of translating an entire sentence into Pig Latin is not trivial. If written in one big method, it would be very long and difficult to follow. A better solution, as implemented in the PigLatinTranslator class, is to decompose the translate method and use several other support methods to help with the task.

The translate method uses a Scanner object to separate the string into words.

The Scanner class is to separate a string into smaller elements called tokens. In this case, the tokens are separated by space characters so we can use the default white space delimiters. The PigLatin program assumes that no punctuation is included in the input.

The methods:

  • translateWord
  • beginsWithVowel
  • beginsWithBlend

Note that instead of checking each vowel separately, the code for this method declares a string that contains all the vowels, and then invokes the String method indexOf to determine whether the first character of the word is in the vowel string. If the specified character cannot be found, the indexOf method returns a value of 1.

The UML class diagram for the PigLatin program if drawn below. Note the notation showing the visibility of various methods.

uml

Static Variables

  • We’ve used static methods. For example, all the methods of the Math class are static. Recall that a static method is one that is invoked through its class name, instead of through an object of that class.
  • Not only can methods be static, but variables can be static as well. We declare static class members using the static modifier.
  • Deciding whether to declare a method or variable as static is a key step in class design.
  • So far, we’ve seen two categories of variables: local variables that are declared inside a method, and instance variables that are declared in a class but not inside a method. The term instance variable is used, because each instance of the class has its own version of the variable. That is, each object has distinct memory space for each variable so that each object can have a distinct value for that variable.
  • A static variable, which is sometimes called a class variable, is shared among all instances of a class. There is only one copy of a static variable for all objects of the class. Therefore, changing the value of a static variable in one object changes it for all of the others.
  • The reserved word static is used as a modifier to declare a static variable as follows:
                       private static int count = 0;
  • Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.

    Here is an example:

    Class test {
       public static String name = "AA";
       private static String age;
    
       public static void setAge(String yourAge) {
           //here if the age variable is not static you will get an error that you cannot access non-static variables from static procedures so you have to make it static and private to not be accessed from other classes
           age = yourAge;
       }
    }
    
    

    screen-shot-2016-10-21-at-7-43-43-am

  • Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
  • A local variable declared within a method cannot be static.
  • Constants, which are declared using the final modifier, are often declared using the static modifier. Because the value of constants cannot be changed, there might as well be only one copy of the value across all objects of the class.

Static Methods

  • A static method is also called a class method. Static methods can be invoked through the class name. We don’t have to instantiate an object of the class in order to invoke the method. We know that all the methods of the Math class are static methods. For example, in the following line of code the sqrt method is invoked through the Math class name:

                      System.out.println (“Square root of 27: ” + Math.sqrt(27));

  • The methods in the Math class perform basic computations based on values passed as parameters. There is no object state to maintain in these situations; therefore, there is no good reason to create an object in order to request these services.
  • A method is made static by using the static modifier in the method declaration.
  • As we’ve seen many times, the main method of a Java program must be declared with the static modifier; this is done so that main can be executed by the interpreter without instantiating an object from the class that contains main.
  • Because static methods do not operate in the context of a particular object, they cannot reference instance variables, which exist only in an instance of a class. The compiler will issue an error if a static method attempts to use a nonstatic variable.
  • A static method can, however, reference static variables, because static variables exist independent of specific objects. Therefore, the main method can access only static or local variables.
  • The program below, SloganCounter instantiates several objects of the Slogan class, printing each one out in turn. At the end of the program it invokes a method called getCount through the class name, which returns the number of Slogan objects that were instantiated in the program.
//********************************************************************
//  SloganCounter.java       Author: Lewis/Loftus
//
//  Demonstrates the use of the static modifier.
//********************************************************************

public class SloganCounter
{
   //-----------------------------------------------------------------
   //  Creates several Slogan objects and prints the number of
   //  objects that were created.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Slogan obj;

      obj = new Slogan ("Remember the Alamo.");
      System.out.println (obj);

      obj = new Slogan ("Don't Worry. Be Happy.");
      System.out.println (obj);

      obj = new Slogan ("Live Free or Die.");
      System.out.println (obj);

      obj = new Slogan ("Talk is Cheap.");
      System.out.println (obj);

      obj = new Slogan ("Write Once, Run Anywhere.");
      System.out.println (obj);

      System.out.println();
      System.out.println ("Slogans created: " + Slogan.getCount());
   }
}


  • The next program shows the Slogan class. The constructor of Slogan increments a static variable called count, which is initialized to zero when it is declared. Therefore, count serves to keep track of the number of instances of Slogan that are created.
  • The getCount method of Slogan is also declared as static, which allows it to be invoked through the class name in the main method.
  • Note that the only data referenced in the getCount method is the integer variable count, which is static.
  • As a static method, getCount cannot reference any nonstatic data.
  • The getCount method could have been declared without the static modifier, but then its invocation in the main method would have to have been done through an instance of the Slogan class instead of the class itself.

 

//********************************************************************
//  Slogan.java       Author: Lewis/Loftus
//
//  Represents a single slogan string.
//********************************************************************

public class Slogan
{
   private String phrase;
   private static int count = 0;

   //-----------------------------------------------------------------
   //  Constructor: Sets up the slogan and counts the number of
   //  instances created.
   //-----------------------------------------------------------------
   public Slogan (String str)
   {
      phrase = str;
      count++;
   }

   //-----------------------------------------------------------------
   //  Returns this slogan as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      return phrase;
   }

   //-----------------------------------------------------------------
   //  Returns the number of instances of this class that have been
   //  created.
   //-----------------------------------------------------------------
   public static int getCount ()
   {
      return count;
   }
}

 

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 – Conditionals more features and assignment

Chapter 3: Program Statements More Notes

While Statement:

whileLoopFC

while ( condition )
{
   // statements block
}

A common mistake: an infinite loop. The loop will keep going forever.

whileStatmt

The do loop:

doFC

do
{
   // statements block
}
while ( condition );

The for loop:

forStatement

forFlowChart

for ( initialization; condition; update )
    {
      // block statements
    }

It is a sign of unbelievably bad taste to put unrelated conditions into the loop. ( lol )

The switch statement

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Class work:
Write a program HollePrinter_YI.java that switches the letters “e” and “o” in a string. Use the replace method repeatedly. Demonstrate that the string “Hello, World!” turns into “Holle, Werld!”

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