Category Archives: Resources

Chapter 5: Goodies Co. Examples

The Goodies Company Project

vendingmachines

From Wikipedia:
In computer programming, an application programming interface (API) is a set of routines, protocols, and tools for building software applications. An API expresses a software component in terms of its operations, inputs, outputs, and underlying types. An API defines functionalities that are independent of their respective implementations, which allows definitions and implementations to vary without compromising the interface. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

Cay Horstmann:
A class should represent a single concept. The public methods
and constants that the public interface exposes should be cohesive.
That is, all interface features should be closely related to the single
concept that the class represents.
If you find that the public interface of a class refers to multiple concepts,
then that is a good sign that it may be time to use separate classes instead.

NO CODE – It is no programming language related!

Examples of public interfaces for the Goodies Company Application:
Example 1:

Class BD_VendingMachine:
public BD_VendingMachine: initializes allocated change and sets profit to 0
void addChange(value) adds allocated change
void addProduct(BD_Product) adds a product to the machine
double getBalance() returns profit
double getChange() returns allocated change remaining
void purchase(BD_Product, double money) buys product inputted and determines change to return, subtracting from allocated change accordingly

Class BD_Product:
public BD_Product(string name, double price)initializes new product and price

Example 2:
Classes:

Class 1 – snack
name, price, stock
can set the name price and amount of the item
can change the price of the item
will decrement the amount when the item is purchased

Class 2 – machine
sales, list of snacks
holds several objects of the class snack
method for purchasing an item which will decrement the snack, increase sales, and output change
method for restocking the amount of a snack
can remove and add snacks
can return the total sales of a machine

Class 3/ Main Class –
runs several of the machines
will buy snacks from various machines
will restock the machines
will check the total sales and amount of snacks in each machine

Example 3:
Vending Machine Project Outline

VendingMachine —> Class
– Array of Products
– Amount initially put in for change
– Total
– Name / Location
addProduct() – allows you to add a product object to the inventory of the machine
addChange() – allows you to add change to the machine
getProfit() – subtracts the added change from the total to display the profit of the machine
buy() – takes in a Product object, and a money value (possibly in coin objets) and allows you to “buy” the product

Product —> Class
– name
– price
getPrice()
getName()
toString()

Coin —> Class
– name
– value
getValue()
getName()
toString()

Example 4:
buyDrink: contains getPrice, giveChange, will give an error message if there are none left
toString: will show everything in the machine and its prices (and quantities?)
addChange: adds to the machine’s change supply w/o buying anything
getQuantity: tells you how many of a drink are in the machine

contains different types of drinks (Drink class?)
takes coins form Coin class

Example 5:
order(x) – The order method is called whenever the user places an order. It decreases the
quantity of the specific item by 1 and adds the price to the overall profit. The item the person
order is given by x, which is an integer that corresponds to the object.
makeChange(x, y) – The makeChange method is always called right after the order method. It
takes in the item as it’s first parameter and the amount the user put into the machine as it’s
second. Then, it returns how much the machine owes the user.
getProfit() – The getProfit method returns the total profit the machine makes.
getQuantity() – The getQuantity method returns the total quantity left of each item in the
machine.

Example 6:
Classes:
endingMachine: This class deals with Product objects and the number of Product objects that exist. This also deals with money taken from the user.
Product: This contains instance variables for different products with their descriptions and prices.
Driver: represents the user’s interaction with the vendingMachine

Methods (VendingMachine):
sellProduct: This method gives a product to the user by lowering the stock of that product and increases profit but checks if the amount of inserted money is enough for the purchase. And if not it refuses it and uses the giveChange method to return the rest.
collectMoney: Collects only the amount of money needed by the machine and allows for sellProduct method.
giveChange: Gives the remaining amount of money that was given but not required to purchase the product.
restockItems: Resets the amount of goods that exist in the vendingmachine.

Product Methods:
getPrice: gives price of product
getProductName: gives the name of the product chosen

Chapter 4: More Concepts

constructors

We don’t have to define a constructor for every class. Each class has a default constructor that takes no parameters and is used if we don’t provide our own. This default constructor generally has no effect on the newly created object.

Local variables

The scope of a variable (or constant) is the part of a program in which a valid reference to that variable can be made. A variable can be declared inside a method, making it local data as opposed to instance data.

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 the appropriate definition.

Note that the return type of a method is not part of the method signature.


They are not intended to provide services directly to clients outside the class. Instead, they exist to help the translate method, which is the only true service method in this class, to do its job. By declaring them with private visibility, they can- not be invoked from outside this class.
A predicate method returns a boolean value:

public boolean isOverdrawn()
{
-->return balance < 0;
}

Used in conditions like

if (harrysChecking.isOverdrawn())

Useful predicate methods in Character class:

isDigit()
isLetter()
isUpperCase()
isLowerCase() 

Classwork:
1. At compilation time an ADT’s constructor gives an error. What do you think might be wrong with it?
2. What is the difference between the variables “balance” and “initial” in this constructor?

 public Account (String owner, int account, double initial)
   {
      name = owner;
      acctNumber = account;
      balance = initial;
   }
  1. What is a method’s signature?
  2. Why would you implement a private method?
  3. Write a private predicate method for this code
         
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));

Chapter 4: Objects Revisited

Chapter 4 – Writing Classes

Concepts to discuss:
keyconcept2

  • attributes, states and instance fields
  • behavior and methods

attributesAndMethods1

methodofaclass4

rollingdiceUML5

keyconcept4

  • object variable and object reference
  • classes as blueprints
  • members of a class

memberofaclass3

 

  • constructors

keyconcept11

 

  • methods

flowofcontrol9

methoddeclaration8

keyconcept8

returnmethod10

keyconcept9

passingpara11

  • access specifiers or visibility modifiers

effectofpublicprivatevisibility7

  • What does a predicate method do? It evaluates the predicate on the value passed to this function as the argument and then returns a boolean value.

keyconcept6

 

  • variable scope

keyconcept3

keyconcept10

 

  • ENCAPSULATION

keyconcept5

 

aclientinteraction6

keyconcept7

Answer the following questions:
Lesson Questions

  1. What is an attribute?
  2. What is an operation?
  3. List some attributes and operations that might be defined for a class called Book that represents a book in a library.
  4. True or False? Explain.
    a. We should use only classes from the Java standard class library when writing our programs—there is no need to define or use other classes.
    b. An operation on an object can change the state of an object.
    c. The current state of an object can affect the result of an operation on that object.
    d. In Java, the state of an object is represented by its methods.
  5. What is the difference between an object and a class?
  6. What is the scope of a variable?
  7. What are UML diagrams designed to do?
  8. Objects should be self-governing. Explain.
  9. What is a modifier?
  10. Describe each of the following:
    ◗ public method
    ◗ private method
    ◗ public variable
    ◗ private variable
  11. What does the return statement do?
  12. Explain the difference between an actual parameter and a formal parameter.
  13. What are constructors used for? How are they defined?
  14. How are overloaded methods distinguished from each other?
  15. What is method decomposition?
  16. Explain how a class can have an association with itself.
  17. What is an aggregate object?

Submit your answers as we discuss them. This assignment will take more than one lesson but submit what you have every time we have the lesson.
 

Chapter 3: Language Basics – Conditionals

Chapter 3: Program Statements Notes

Control Flow:

  1. A conditional statement is sometimes called a selection statement.
  2. Each decision is based on a boolean expression.
  3. Three types of loop statements: while, do and for statements.

The if statement:

ifStatementFlowChart

Shorthand “if” statement: a ternary operator, inline if a or ternary

y = ( x <= 0 ) ? x : -x

which is a convenient way of writing

if ( x <= 0 )

y = x; else y = -x …..
  1. Equality operators
  2. Relational operators
equalityRelationOps The if-else statement: ifElseStatemtFC Nested if statements:
if (a < b)
   if (a < c)
      x = a;
   else
      x = c;
else
   if (b < c)
      x = b;
   else
      x = c;

Classwork: you can use this code snippet to write a program minMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest.Write the test/driver program if you use OOD.
NOTE: Assume the numbers are different. Include this assumption in your documentation.

Boolean expressions:

Logical operators:

logicalOps

Truth Table:

truthTable

Logical AND and OR operators:

andOrTruthTable

 

Example of truth table for a specific condition:

truthTableExample

 

Booelean Expression Exercise: Work on this boolean expression using the table attached here Builtintypestruthtable2
. Visit Canvas to access the doc version.

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 )

Assignment:
Using the code snippet from the lesson write a program MinMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest. OOP is not required. However, write the test/driver program if you use OOD.

Assignment: Programming Project 3.2
Design and implement an application that reads an integer value representing a year input by the user. The purpose of the program is to determine if the year is a leap year (and therefore has 29 days in February) in the Gregorian calendar. A year is a leap year if it is divisible by 4 unless it is also divisible by 100 but not 400. For example, the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100, but the year 2000 is a leap year because even though it is divisible by 100, it is also divisible by 400. Produce an error message for any input value less than 1582 (the year the Gregorian calendar was adopted).

Reading and Writing Assignments:

Read pages 124 through 140, submit the short answers 3.1 through 3.5.

Short Answers:

3.1 What happens in the MinOfThree program if two or more of
the values are equal? If exactly two of the values are equal, does
it matter whether the equal values are lower or higher than the
third?

3.2 What is wrong with the following code fragment? Rewrite it so
that it produces correct output.

if (total == MAX)
    if (total < sum)
       System.out.println ("total == MAX and is < sum.");
    else
       System.out.println ("total is not equal to MAX");

3.3 What is wrong with the following code fragment? Will this code
compile if it is part of a valid program? Explain.

if (length == MIN_LENGTH)
   System.out.println ("The length is minimal.");

3.4 What output is produced by the following code fragment?

int num = 87, max = 25;
if (num >= max*2)
System.out.println ("apple");
System.out.println ("orange");
System.out.println ("pear");

3.5 What output is produced by the following code fragment?

int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit)
{
if (num1 == num2)
System.out.println ("lemon");
System.out.println ("lime");
}
System.out.println ("grape");

Tying up lose ends for the AP Exam

What is null in Java?

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

Autoboxing and Unboxing

Review Wish list:
built in types >> primitive data type
hexadecimal and octal numbers
stacks and cues
operators >> assignment
escape sequences: \n \” \
boolean algebra
STATIC (everything)
try catch exceptions (throwing exceptions)
INHERITANCE
POLYMORPHISM
type compatibility (down casting abstract classes)
Wrapper class
syntax for arrays vs array list
2d array syntax
tracing recursive methods
SORTS >> selection, insertion, merge, quick
SEARCHES >> binary, sequential
Big O Notation

Chapter 8: Sorts Projects

Classwork:
The purpose of this assignment is to observe the different performance of the quick sort based on the data.

  1. Create 3 data sets of 50,000 integers:

Data Set A: randomly generate the data in range from 1 to 50,000.(no duplicates)
Data Set B: generate integers in range from 1 to 50,000 sorted in ascending order.
Data Set C: generate integers in range from 1 to 50,000 sorted in descending order.

  1. Set up a counter in your quick sort trace program and run the three sets separately.
    Your results will be meaningful depending where you put the counter. So be mindful of what you are trying to achieve.

  2. Find an expression that relates the size of the data to the number of comparisons or visits to the data.

  3. Make a conclusion about the three different cases.

NOTE: Use Arrays and the version of Quick sort we have used.

**** If your program crashes with “stack overflow”, change the number of elements from 50,000 to 10,000 ****

Documentation:
Besides the usual, explain where and why your counter is placed.
The conclusion about the behavior of the sort based on the data characteristic.

Sorting Project
Due date: February 15th, 2017

You are to write a program that tests each of five sorting algorithms with arrays of random integer values of four different sizes. You also need a counter for this project. And just like in the previous assignment you need to decide where the counter should be so the comparisons make sense for the all the sorts. The documentation must explain where and why the counter is placed.

The five algorithms are: selection sort, insertion sort, bubble sort, quick sort and merge sort.
The array sizes to use are: 10, 100, 1000, and 5000.
The Counter class and also a class that generates arrays of random integers are posted below.
You will need to modify the sort code to include an increment to the counter where appropriate.

The main part of this project is the design and implementation of a driver program that will test the sorts on the same set of arrays.

  1. It should keep track of the count result for each sort for each array size and generate a table to summarize the results. A sample table is shown.

  1. It should create a scatter plot for each of the sorts. The plot could be either text based or as a GUI. You have the option of entering the data in a spreadsheet and use the graphing feature to create the scatter plot.

  1. Use mathematical regressions to find an expression for each of the sorts’ data.

NOTE: Counter, RandomIntArray classes, and public static void bubbleSort1(int[] x) resources are optional. You can make substitutions.

import java.util.Scanner;
//********************************************************************
//  RecursiveSorts.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the merge sort and quick sort algorithms.
//********************************************************************

public class RecursiveSorts
{
   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using merge sort.
   //-----------------------------------------------------------------
   public static void mergeSort (int[] numbers)
   {
       
      doMergeSort(numbers, 0, numbers.length - 1);
   }

   //-----------------------------------------------------------------
   //  Recursively sorts the the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doMergeSort (int[] numbers, int start, int end)
   {
       
      if (start < end)
      {
         int middle = (start + end) / 2;
         doMergeSort (numbers, start, middle);
         doMergeSort (numbers, middle + 1, end);
         merge (numbers, start, middle, end);
      }
   }

   //-----------------------------------------------------------------
   //  Merges in sorted order the two sorted subarrays
   //  [start, middle] and [middle + 1, end].
   //-----------------------------------------------------------------
   private static void merge (int[] numbers, int start, int middle,
                     int end)
   {

      // This temporary array will be used to build the merged list.
      int[] tmp = new int[end - start + 1];

      int index1 = start;
      int index2 = middle + 1;
      int indexTmp = 0;

      // Loop until one of the sublists is exhausted, adding the smaller
      // of the first elements of each sublist to the merged list.
      while (index1 <= middle && index2 <= end)
      {
         if (numbers[index1] < numbers[index2])
         {
             tmp[indexTmp] = numbers[index1];
             index1++;
         }
         else
         {
             tmp[indexTmp] = numbers[index2];
             index2++;
         }
          indexTmp++;
      }

      // Add to the merged list the remaining elements of whichever sublist
      // is not yet exhausted.
      while (index1 <= middle)
      {
         tmp[indexTmp] = numbers[index1];
         index1++;
         indexTmp++;
      }
      while (index2 <= end)
      {
         tmp[indexTmp] = numbers[index2];
         index2++;
         indexTmp++;
      }


      // Copy the merged list from tmp into numbers.
      for (indexTmp = 0; indexTmp < tmp.length; indexTmp++)
      {
         numbers[start + indexTmp] = tmp[indexTmp]; 
      }

   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using quick sort.
   //-----------------------------------------------------------------
   public static void quickSort (int[] numbers)
   {
      doQuickSort(numbers, 0, numbers.length - 1);
   }
   //-----------------------------------------------------------------
   //  Recursively sorts the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doQuickSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = partition(numbers, start, end);
         doQuickSort(numbers, start, middle);
         doQuickSort(numbers, middle + 1, end);
      }
   }

   //-----------------------------------------------------------------
   //  Partitions the array such that each value in [start, middle]
   //  is less than or equal to each value in [middle + 1, end].
   //  The index middle is determined in the procedure and returned.
   //-----------------------------------------------------------------
   private static int partition (int[] numbers, int start, int end)
   {
      int pivot = numbers[start];
      int i = start - 1;
      int j = end + 1;

      // As the loop progresses, the indices i and j move towards each other.
      // Elements at i and j that are on the wrong side of the partition are
      // exchanged. When i and j pass each other, the loop ends and j is
      // returned as the index at which the elements are partitioned around.
      while (true)
      {
         i = i + 1;
         while (numbers[i] < pivot)
            i = i + 1;

         j = j - 1;
         while (numbers[j] > pivot)
            j = j - 1;

         if (i < j)
         {
            int tmp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tmp;

            for (int index = 0; index < numbers.length; index++)
                System.out.print (numbers[index] + "   ");
         }
         else return j;
      }
   }
}

Bubble Sort — fixed number of passes
This version of bubble sort makes a fixed number of passes (length of the array – 1). Each inner loop is one shorter than the previous one.

public static void bubbleSort1(int[] x) {
    int n = x.length;
    for (int pass=1; pass < n; pass++) {  // count how many times
        // This next loop becomes shorter and shorter
        for (int i=0; i < n-pass; i++) {
            if (x[i] > x[i+1]) {
                // exchange elements
                int temp = x[i];  
                x[i] = x[i+1];  
                x[i+1] = temp;
            }
        }
    }
}

Optional Resources:

public class Counter

{
    private static int count = 0;

    public static int getcount( )

    {
        return count;
    }

    public static void reset( )
    {
        count = 0;
    }

    public static void increment( )
    {
        count++;
    }
}
import java.util.Random;

public class RandomIntArray
{
    public static int[ ] generateArray( int n )
    {
    // generates an array of length n populated
    // with random integers

        int[ ] result = new int[n];
                Random random = new Random();
        for (int i = 0; i < n; i++)

            result[i] = random.nextInt(5*n);

        return result;
    }
}


Homework:
Start working on the project.