Category Archives: Class work

Chapter 5: Interfaces – Zero ADT

Exception Handling
An exception is an object created to handle unusual or specific errors.
An exception is thrown by a program or the run-time environment.
An exception can be caught and handled appropriately when needed.
An error is similar to an exception except that an error runs its course.
Java has a predefined set of exceptions and errors that may occur during the execution of a program.

zeromile

//********************************************************************
//  Zero.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates an uncaught exception.
//********************************************************************

public class Zero
{
   //-----------------------------------------------------------------
   //  Deliberately divides by zero to produce an exception.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int numerator = 10;
      int denominator = 0;

      System.out.println (numerator / denominator);

      System.out.println ("This text will not be printed.");
   }
}

Run Zero.java. Does it compile? Does it run?
Answer this question in edmodo.com

/**
 * This class demonstrates the use of exception classes
 * 
 * @Lewis/Loftus/Cocking/Elia
 * @10/21/14
 */
public class ExceptionsExample
{
    
    //********************************************************************
//  Zero.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates an uncaught exception and how to handle it
//********************************************************************

   //-----------------------------------------------------------------
   //  Deliberately divides by zero to produce an exception during runtime.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int numerator = 10;
      int denominator = 0;

      //System.out.println (numerator / denominator);

      //.out.println ("This text will not be printed.");
      
      // handling the exception with try and catch
      
      
      try
         {
            System.out.println (numerator / denominator);
         }
         catch (ArithmeticException e)
         {
            System.out.println ("Improper denominator input validation");
         }
         catch (NumberFormatException exception)
         {
            System.out.println ("Improper number format");
         }
      
   }
}

/**
 * output: Improper denominator input validation
 */



Interfaces

A Java interface is a collection of constants and abstract methods.
An interface cannot be instantiated.
A class implements an interface by providing method implementations for each of the abstract methods defined in the interface.
Methods in interfaces have public visibility by default.

In addition to, or instead of, abstract methods, an interface can also contain constants, defined using the final modifier. When a class implements an inter- face, it gains access to all the constants defined in it.

An interface is represented similarly to a class node except that the designation

 <> 

is inserted above the interface name. A dotted arrow with a closed arrowhead is drawn from the class to the interface that it implements.

Screen Shot 2014-10-21 at 1.53.23 PM

//********************************************************************
//  Complexity.java       Author: Lewis/Loftus/Cocking
//
//  Represents the interface for an object that can be assigned an
//  explicit complexity.
//********************************************************************

public interface Complexity
{
   public void setComplexity (int complexity);
   public int getComplexity();
}

 

//********************************************************************
//  Question.java       Author: Lewis/Loftus/Cocking
//
//  Represents a question (and its answer).
//********************************************************************

public class Question implements Complexity
{
   private String question, answer;
   private int complexityLevel;

   //-----------------------------------------------------------------
   //  Sets up the question with a default complexity.
   //-----------------------------------------------------------------
   public Question (String query, String result)
   {
      question = query;
      answer = result;
      complexityLevel = 1;
   }

   //-----------------------------------------------------------------
   //  Sets the complexity level for this question.
   //-----------------------------------------------------------------
   public void setComplexity (int level)
   {
      complexityLevel = level;
   }

   //-----------------------------------------------------------------
   //  Returns the complexity level for this question.
   //-----------------------------------------------------------------
   public int getComplexity()
   {
      return complexityLevel;
   }

   //-----------------------------------------------------------------
   //  Returns the question.
   //-----------------------------------------------------------------
   public String getQuestion()
   {
      return question;
   }
   //-----------------------------------------------------------------
   //  Returns the answer to this question.
   //-----------------------------------------------------------------
   public String getAnswer()
   {
      return answer;
   }

   //-----------------------------------------------------------------
   //  Returns true if the candidate answer matches the answer.
   //-----------------------------------------------------------------
   public boolean answerCorrect (String candidateAnswer)
   {
      return answer.equals(candidateAnswer);
   }

   //-----------------------------------------------------------------
   //  Returns this question (and its answer) as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      return question + "\n" + answer;
   }
}

Replace the Keyboard Class with Scanner

//********************************************************************
//  MiniQuiz.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a class that implements an interface.
//********************************************************************



public class MiniQuiz
{
   //-----------------------------------------------------------------
   //  Presents a short quiz.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Question q1, q2;
      String possible;

      q1 = new Question ("What is the capital of Jamaica?",
                         "Kingston");
      q1.setComplexity (4);

      q2 = new Question ("Which is worse, ignorance or apathy?",
                         "I don't know and I don't care");
      q2.setComplexity (10);

      System.out.print (q1.getQuestion());
      System.out.println (" (Level: " + q1.getComplexity() + ")");
      possible = Keyboard.readString();
      if (q1.answerCorrect(possible))
         System.out.println ("Correct");
      else
         System.out.println ("No, the answer is " + q1.getAnswer());

      System.out.println();
      System.out.print (q2.getQuestion());
      System.out.println (" (Level: " + q2.getComplexity() + ")");
      possible = Keyboard.readString();
      if (q2.answerCorrect(possible))
         System.out.println ("Correct");
      else
         System.out.println ("No, the answer is " + q2.getAnswer());
   }
}


 

Classwork:
1. What is the difference between an error and an exception?
2. What is the difference between a class and an interface?
3. Define a Java interface called Nameable. Classes that implement this interface must provide a setName method that requires a single String parameter and returns nothing, and a getName method that has no parameters and returns a String.
4. True or False? Explain.
a. A Java interface can include only abstract methods, nothing else.
b. An abstract method is a method that does not have an implementation.
c. All of the methods included in a Java interface definition must be
abstract.
d. A class that implements an interface can define only those methods
that are included in the interface.
e. Multiple classes can implement the same interface.
f. A class can implement more than one interface.
g. All classes that implement an interface must provide the exact
same definitions of the methods that are included in the interface.

Read up to pages 263 through 269 from Chapter 5.

 

 

Chapter 5: Interface Lockable – Comparable

January 3rd, 2018

Classwork:

lock

Programming Project 5.6:
Design a Java interface called Lockable that includes the following methods: setKey, lock, unlock, and locked. The setKey, lock, and unlock methods take an integer parameter that represents the key. The setKey method establishes the key. The lock and unlock methods lock and unlock the object, but only if the key passed in is correct. The locked method returns a boolean that indicates whether or not the object is locked. A Lockable object represents an object whose regular methods are protected: if the object is locked, the methods cannot be invoked; if it is unlocked, they can be invoked. Redesign and implement a version of the Coin class from Chapter 4 so that it is Lockable.
Include a driver.

Homework:
Programming Project 5.7:
Redesign and implement a version of the Account class from Chapter 4 so that it is Lockable as defined by Programming Project 5.6.
Include a driver.

Chapter 5: Inner Classes – Nested Classes

January 12th, 2017

Classwork:

Inner Classes – Nested Classes
A class can be declared inside another class. Just as a loop written inside another loop is called a nested loop, a class written inside another class is called a nested class. The nested class is considered a member of the enclosing class, just like a variable or method.

  • Just like any other class, a nested class produces a separate bytecode file.
  • The name of the bytecode file is the name of the enclosing class followed by the $ character followed by the name of the nested class.
  • Like any other bytecode file, it has an extension of .class. A class called Nested that is declared inside a class called Enclosing will result in a compiled bytecode file called Enclosing$Nested.class.
  • Because it is a member of the enclosing class, a nested class has access to the enclosing class’s instance variables and methods, even if they are declared with private visibility.
  • The enclosing class can directly access data in the nested class only if the data is declared public.
  • Data should always be kept private to follow the rules of encapsulation. However, the exception applies to nested class so the enclosing class can get to the data.
  • Such a privileged relationship should be reserved for appropriate situations.
  • The static modifier can be applied to a class, but only if the class is nested inside another.
  • Like static methods, a static nested class cannot reference instance variables or methods defined in its enclosing class.
  • //********************************************************************
    //  TestInner.java       Author: Lewis/Loftus
    //
    //  Demonstrates the access capabilities of inner classes.
    //********************************************************************
       public class TestInner
       {
          //-----------------------------------------------------------------
          //  Creates and manipulates an Outer object.
          //-----------------------------------------------------------------
          public static void main (String[] args)
          {
             Outer out = new Outer();
             System.out.println (out);
             System.out.println();
             out.changeMessages();
             System.out.println (out);
          } 
       }
    

    Output
    Copy these files to your project.
    Show and explain the output on edmodo.com

    
    //********************************************************************
    //  Outer.java       Author: Lewis/Loftus
    //
    //  Represents a class that encapsulates an inner class.
    //********************************************************************
    public class Outer
    {
       private int num;
       private Inner in1, in2;
       //-----------------------------------------------------------------
       //  Sets up this object, initializing one int and two objects
       //  created from the inner class.
       //-----------------------------------------------------------------
       public Outer()
       {
         num = 9876;
         in1 = new Inner ("Half of the problem is 90% mental.");
         in2 = new Inner ("Another deadline. Another miracle.");
       }
       //-----------------------------------------------------------------
       //  Changes the messages in the Inner objects (directly).
       //-----------------------------------------------------------------
       public void changeMessages()
       {
          in1.message = "Life is uncertain. Eat dessert first.";
          in2.message = "One seventh of your life is spent on Mondays.";
       }
       //*****************************************************************
       //  Returns this object                
       //*****************************************************************
    
       public String toString()
       {
          return in1 + "\n" + in2;
       }
    
          //*****************************************************************
          //  Represents an inner class.
          //*****************************************************************
          private class Inner
          {
             public String message;
             //--------------------------------------------------------------
             //  Sets up this Inner object with the specified string.
             //--------------------------------------------------------------
             public Inner (String str)
             {
                message = str;
             }
             //--------------------------------------------------------------
             //  Returns this object as a string, including a value from
             //  the outer class.
             //--------------------------------------------------------------
             public String toString()
             {
                num++;
                return message + "\nOuter num = " + num;
             }
           }
       }
        
    
  • Each Inner object contains a public String called message.
  • Because it is public, the changeMessages of the Outer class can reach in and modify the contents.
  • As the authors’ve stressed many times, giving data public access should be avoided in general. However, in this case, since Inner is a private class, no class other than Outer can refer to it. Therefore no class other than Outer can directly access the public data inside it either.
    Using inner classes with public data should be done only in situations in which the outer class is completely dependent on the inner class for its existence.

    If designed properly, inner classes preserve encapsulation while simplifying the implementation of related classes

    Preparing for chapter 5 test on Wednesday and getting ready for Midterm.

    Homework:
    Study for chapter 5 test.

    Chapter 5: Goodies Co. – The requirements

    Design an application Phase 1 – The business model:

    vendingmachines

    The Goodies Co. maintains a kiosk at a busy location with other competing kiosks. This vending front sells snacks and beverages only. Mrs. Goodies has been operating it manually but she wants to have an automated system that would allow her to manage the kiosk more efficiently.

    The client’s requirements at a glance are as follow:
    It should have two interfaces: one for the customer and another for the business operation.

    Sample of a day’s activity:
    Welcome to Goodies Vending Store
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 1

    Business Operations
    1. View Inventory
    2. Re-stock
    3. blah blah …
    4. blah blah …
    5. Back to the main menu
    6. Exit Goodies Vending Store
    What is your choice? 5

    Welcome to Goodies Vending Store
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 2

    Welcome to Goodies Vending Store
    Here are your choices:
    1. Drinks
    2. Drygoods
    3. Frozen delights
    4. blah blah
    5. Back to the main menu
    6. Done with purchases
    7. Exit Goodies Vending Store
    1 –> drinks menu should come up

    Prompt the buyer for more purchases or to go back to the main menu.

    What is your choice? 5
    Your total is $22.75

    Bye! See you soon.
    It was a pleasure to serve you!

    Customer Interface

    • Available products and price should be displayed numerically as a text menu.
    • The customer should be able to access the product by pressing a key with a number
    • The customer should be prompted for option number.
    • Payment can be assumed to be exact and correct.
    • Handle payment.
    • Update sales record(s).
    • Update kiosk inventory.
    • Back to customer menu.
    • Prompt the user for product number? Exit?
    • If exit, it should go back to the START of operiations.

    Business Operations

    • The Business Operations should only be accessed by password (Optional)
    • The system should know the quantity, cost, and selling price for each product.
    • It should keep a current inventory of the products in the kiosk and in stock.
    • It should have re-stocking(s) notification(Optional)
    • It should have an option to re-stock both the store and the stockpile
    • Update stockpile inventory
    • It should access information of the net profits based on the sales on demand.

    The START of Operations

    • Welcome message.
    • Load data base of products and prices.
    • Menu: Customer? Business Operations?
    • Chose?/Exit?

    The END of Operations

    • Update database with current quantities.
    • Prompt the business manager for stockpile re-stocking
    • Close database files
    • Goodbye message

    Assumptions

    • Payment is exact and correct.
    • Products pricess never change

    Chapter 5: Measurable Interface

    DataSet

    /**
       Computes the average of a set of data values.
    */
    public class DataSet
    {
       /**
          Constructs an empty data set.
       */
       public DataSet()
       {
          sum = 0;
          count = 0;
          maximum = 0;
       }
    
       /**
          Adds a data value to the data set
          @param x a data value
       */
       public void add(double x)
       {
          sum = sum + x;
          if (count == 0 || maximum < x) maximum = x;
          count++;
       }
    
       /**
          Gets the average of the added data.
          @return the average or 0 if no data has been added
       */
       public double getAverage()
       {
          if (count == 0) return 0;
          else return sum / count;
       }
    
       /**
          Gets the largest of the added data.
          @return the maximum or 0 if no data has been added
       */
       public double getMaximum()
       {
          return maximum;
       }
    
       private double sum;
       private double maximum;
       private int count;
    }
    
    

    [collapse]
    BankAccount

    /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount
    {  
        
       private double balance;
       private String name;
       
    
       /**
          Constructs a bank account with a zero balance
       */
       public BankAccount()
       {   
          balance = 0;
          name = "    ";
       }
    
       /**
          Constructs a bank account with a given balance
          @param initialBalance the initial balance
       */
       public BankAccount(double initialBalance, String aName)
       {   
          balance = initialBalance;
          name = aName;
       }
    
       /**
          Deposits money into the bank account.
          @param amount the amount to deposit
       */
       public void deposit(double amount)
       {  
          double newBalance = balance + amount;
          balance = newBalance;
       }
    
       /**
          Withdraws money from the bank account.
          @param amount the amount to withdraw
       */
       public void withdraw(double amount)
       {   
          double newBalance = balance - amount;
          balance = newBalance;
       }
    
       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }
    
    }
    
    

    [collapse]
    Coin

    /**
       A coin with a monetary value.
    */
    public class Coin
    {
       /**
          Constructs a coin.
          @param aValue the monetary value of the coin.
          @param aName the name of the coin
       */
       public Coin(double aValue, String aName) 
       { 
          value = aValue; 
          name = aName;
       }
    
       /**
          Gets the coin value.
          @return the value
       */
       public double getValue() 
       {
          return value;
       }
    
       /**
          Gets the coin name.
          @return the name
       */
       public String getName() 
       {
          return name;
       }
    
       private double value;
       private String name;
    }
    
    

    [collapse]
    BankDataSet

    /**
       Computes the average of a set of data values.
    */
    public class BankDataSet
    {
       /**
          Constructs an empty data set.
       */
       public BankDataSet()
       {
          sum = 0;
          count = 0;
          maximum = null;
       }
    
       /**
          Adds a bank account balance to the data set
          @param x a data value
       */
       public void add(BankAccount bkAcc)
       {
          sum = sum + bkAcc.getBalance();
          if (count == 0 || maximum.getBalance() < bkAcc.getBalance()) maximum = bkAcc;
          count++;
       }
    
       /**
          Gets the average of the added data.
          @return the average or 0 if no data has been added
       */
       public double getAverage()
       {
          if (count == 0) return 0;
          else return sum / count;
       }
    
       /**
          Gets the largest of the added data.
          @return the maximum or 0 if no data has been added
       */
       public BankAccount getMaximum()
       {
          return maximum;
       }
    
       private double sum;
       private BankAccount maximum;
       private int count;
    }
    
    

    [collapse]
    CoinDataSet
    /**
       Computes the average of a set of data values.
    */
    public class CoinDataSet
    {
       /**
          Constructs an empty data set.
       */
       public CoinDataSet()
       {
          sum = 0;
          count = 0;
          maximum = null;
       }
    
       /**
          Adds a bank account balance to the data set
          @param x a data value
       */
       public void add(Coin aCoin)
       {
          sum = sum + aCoin.getValue();
          if (count == 0 || maximum.getValue() < aCoin.getValue()) maximum = aCoin;
          count++;
       }
    
       /**
          Gets the average of the added data.
          @return the average or 0 if no data has been added
       */
       public double getAverage()
       {
          if (count == 0) return 0;
          else return sum / count;
       }
    
       /**
          Gets the largest of the added data.
          @return the maximum or 0 if no data has been added
       */
       public Coin getMaximum()
       {
          return maximum;
       }
    
       private double sum;
       private Coin maximum;
       private int count;
    }
    
    

    [collapse]

    Measurable

    /**
     * Interface Measurable: use the implements keyword to indicate that a class 
     * implements an interface type. Unlike a class, an interface type provides no implementation
     * @GE
     * @12/15/17
     */
    
    /**
       Describes any class whose objects can be measured.
    */
    public interface Measurable
    {
       /**
          Computes the measure of the object.
          @return the measure
       */
       double getMeasure();
    }
    
    
    

    [collapse]

    BankAccount

    /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount implements Measurable
    {  
       /**
          Constructs a bank account with a zero balance
       */
       public BankAccount()
       {   
          balance = 0;
       }
    
       /**
          Constructs a bank account with a given balance
          @param initialBalance the initial balance
       */
       public BankAccount(double initialBalance)
       {   
          balance = initialBalance;
       }
    
       /**
          Deposits money into the bank account.
          @param amount the amount to deposit
       */
       public void deposit(double amount)
       {  
          double newBalance = balance + amount;
          balance = newBalance;
       }
    
       /**
          Withdraws money from the bank account.
          @param amount the amount to withdraw
       */
       public void withdraw(double amount)
       {   
          double newBalance = balance - amount;
          balance = newBalance;
       }
    
       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }
    
       public double getMeasure()
       {
          return balance;
       }
    
       private double balance;
    }
    
    

    [collapse]

    Coin
    /**
       A coin with a monetary value.
    */
    public class Coin implements Measurable
    {
       /**
          Constructs a coin.
          @param aValue the monetary value of the coin.
          @param aName the name of the coin
       */
       public Coin(double aValue, String aName) 
       { 
          value = aValue; 
          name = aName;
       }
    
       /**
          Gets the coin value.
          @return the value
       */
       public double getValue() 
       {
          return value;
       }
    
       /**
          Gets the coin name.
          @return the name
       */
       public String getName() 
       {
          return name;
       }
    
       public double getMeasure() 
       {
          return value;
       }
    
       private double value;
       private String name;
    }
    
    

    [collapse]

    DataSet

    /**
       Computes the average of a set of data values.
    */
    public class DataSet
    {
       /**
          Constructs an empty data set.
       */
       public DataSet()
       {
          sum = 0;
          count = 0;
          maximum = null;
       }
    
       /**
          Adds a data value to the data set
          @param x a data value
       */
       public void add(Measurable x)
       {
          sum = sum + x.getMeasure();
          if (count == 0 || maximum.getMeasure() < x.getMeasure())
             maximum = x;
          count++;
       }
    
       /**
          Gets the average of the added data.
          @return the average or 0 if no data has been added
       */
       public double getAverage()
       {
          if (count == 0) return 0;
          else return sum / count;
       }
    
       /**
          Gets the largest of the added data.
          @return the maximum or 0 if no data has been added
       */
       public Measurable getMaximum()
       {
          return maximum;
       }
    
       private double sum;
       private Measurable maximum;
       private int count;
    }
    
    

    [collapse]

    DataSetTest

    /**
       This program tests the DataSet class.
    */
    public class DataSetTest
    {
       public static void main(String[] args)
       {
          DataSet bankData = new DataSet();
          
          bankData.add(new BankAccount(3000));
          bankData.add(new BankAccount(10000));
          bankData.add(new BankAccount(2000));
    
          System.out.println("Average balance = " 
             + bankData.getAverage());
          
          Measurable max = bankData.getMaximum();
          System.out.println("Highest balance = " 
             + max.getMeasure());
          //System.out.println("Get bank balance = " 
          //   + max.getBalance());
          BankAccount maxAccount = (BankAccount) max;
          System.out.println("Get bank balance = " 
             + maxAccount.getBalance());
    
          DataSet coinData = new DataSet();
    
          coinData.add(new Coin(0.25, "quarter"));
          coinData.add(new Coin(0.1, "dime"));
          coinData.add(new Coin(0.05, "nickel"));
    
          System.out.println("Average coin value = " 
             + coinData.getAverage());
         
          max = coinData.getMaximum();
          System.out.println("Highest coin value = " 
             + max.getMeasure());
         
       }
    }
    
    

    [collapse]

    Classwork: Create a class Student that realizes the Measurable interface. Add to the driver, DataSetTest a data set of students. Print the average, the max value and the name of the student.
    Submit to “Measurable – Interfaces Lesson Practice” post the following files (you can attach them): BankAccount, Coin, Student, DataSet and DataSetTest. Make sure the output is included in the test class as comment.

    //********************************************************************
    //  Student.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a college student.
    //********************************************************************
    
    public class Student
    {
       private String firstName, lastName;
       private double GPA; // for Measurable Interface purpose
    
       //-----------------------------------------------------------------
       //  Sets up this Student object with the specified initial values.
       //-----------------------------------------------------------------
       public Student (String first, String last, double aGPA)
       {
          firstName = first;
          lastName = last;
          GPA = aGPA;
       }
    
       public String getName()
       {
          return firstName + " " + lastName + "\n";
       }
       //-----------------------------------------------------------------
       //  Returns this Student object as a string.
       //-----------------------------------------------------------------
       public String toString()
       {
          String result;
    
          result = firstName + " " + lastName + "\n";
          result += GPA
    
          return result;
       }
    }
    
    
    
    
    

    Assignments:
    Programming Projects 5.3 and 5.4

    Chapter 5: References Revisited

    References revisited:

    – An object reference variable and an object are two different things.
    – The declaration of the reference variable and the creation of the object that it refers to are separate steps.
    – The dot operator uses the address in the reference variable.
    – A reference variable that doesn’t point to an object is called a null reference.
    – When a reference variable is first declared as an instance variable, it is a null reference.
    – Accessing a null reference will cause a NullPointerException.

    What is the problem with this class?

    1. public class ACommonMistake
    2.{
    3.  public ACommonMistake()
    4.  {
    5.    System.out.println(lastName.length());
    6.  }
    
    7.  public void aMethod()
    8.   {
    9.    String firstName;
    10.   System.out.println(firstName.length());
    11.  }
    
    12. private String lastName;
    13.}

    The this reference:
    – The “this” word is a reserved word in Java.
    – It lets an object refer to itself.
    – A method is always invoked through (or by) a particular object or class.
    – Inside the method, the “this” reference can be used to refer the currently executing object.

    Aliases:
    An object reference variable stores an address therefore an assignment like this:

    ChessPiece bishop1 = new ChessPiece();
    ChessPiece bishop2 = bishop1;
    Will make the two object variables refer to the same object.

    Method Parameters Revisited:

    In Java, all parameters are passed by value. That is, the current value of the actual parameter (in the invocation) is copied into the formal parameter in the method header.

    //********************************************************************
    //  ParameterTester.java       Author: Lewis/Loftus
    //
    //  Demonstrates the effects of passing various types of parameters.
    //********************************************************************
    
    public class ParameterTester
    {
       //-----------------------------------------------------------------
       //  Sets up three variables (one primitive and two objects) to
       //  serve as actual parameters to the changeValues method. Prints
       //  their values before and after calling the method.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          ParameterModifier modifier = new ParameterModifier();
    
          int a1 = 111;
          Num a2 = new Num (222);
          Num a3 = new Num (333);
    
          System.out.println ("Before calling changeValues:");
          System.out.println ("a1\ta2\ta3");                       
          System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n");   // 1st print
    
          modifier.changeValues (a1, a2, a3);
    
          System.out.println ("After calling changeValues:");
          System.out.println ("a1\ta2\ta3");
          System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n");  // 4th print
       }
    }
    
    //********************************************************************
    //  ParameterModifier.java       Author: Lewis/Loftus
    //
    //  Demonstrates the effects of changing parameter values.
    //********************************************************************
    
    public class ParameterModifier
    {
       //-----------------------------------------------------------------
       //  Modifies the parameters, printing their values before and
       //  after making the changes.
       //-----------------------------------------------------------------
       public void changeValues (int f1, Num f2, Num f3)
       {
          System.out.println ("Before changing the values:");
          System.out.println ("f1\tf2\tf3");
          System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n");  // 2nd print
    
          f1 = 999;
          f2.setValue(888);
          f3 = new Num (777);
    
          System.out.println ("After changing the values:");
          System.out.println ("f1\tf2\tf3");
          System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n");  // 3rd print
       }
    }
    
    
    //********************************************************************
    //  Num.java       Author: Lewis/Loftus
    //
    //  Represents a single integer as an object.
    //********************************************************************
    
    public class Num
    {
       private int value;
    
       //-----------------------------------------------------------------
       //  Sets up the new Num object, storing an initial value.
       //-----------------------------------------------------------------
       public Num (int update)
       {
          value = update;
       }
    
       //-----------------------------------------------------------------
       //  Sets the stored value to the newly specified value.
       //-----------------------------------------------------------------
       public void setValue (int update)
       {
          value = update;
       }
    
       //-----------------------------------------------------------------
       //  Returns the stored integer value as a string.
       //-----------------------------------------------------------------
       public String toString ()
       {
          return value + "";
       }
    }
    
    

    output1

    output2

    in main

    in memory

    passing parameters

    Classwork:
    1. Why does a3 end up with 333 and not 777?
    2. Why a1 isn’t 999 after execution of ParameterTester?
    3. Does a1 ever change to 999?
    4. Why does a2 change to 888?
    5. When does a2 change to 888?
    6. Why can a2 change to a different value while a1 and a3 can’t?

     

    Chapter 5: The Goodies Co. – Next step

    The Goodies Company Project

    vendingmachines

    Designing and Implementing – Phase 1:
    1. Use your questions and answers as a guide to define the signature of every class’ method.
    2. Draw a UML class diagram for your entire application. Make sure you follow the rules for UML.
    NOTE: You can use google doc drawing or just a word doc.
    .
    goodies-Class-Digram-phase-2-2
    .
    .
    UMLBasics-arrows
    .
    .
    Here is the link to a UML builder you used before.
    www.umletino.com

    Using your Design/UML, implement the Business Operations application for the business owner/manager/bookkeeper/accountant to operate the business.

    Day 3: The user interface
    Write a program (main) that displays multiple menus.
    Example of a simplified session to start your code:

    Welcome to Goodies Vending System
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 1

    Business Operations
    1. View Inventory
    2. Re-stock
    3. blah blah …
    4. blah blah …
    5. Back to the main menu
    6. Exit Goodies Vending System
    What is your choice? 5

    Welcome to Goodies Vending System
    1. Business Operation
    2. Customer
    3. Exit
    What is your choice? 2

    Welcome to Goodies Vending Machine
    Here are your choices:
    1. Drinks
    2. Drygoods
    3. Frozen delights
    4. blah blah …
    5. Back to the main menu
    6. Done with purchases
    7. Exit Goodies Vending System
    1 –> drinks menu should come up
    Prompt the buyer for more purchases or to go back to the main menu.

    What is your choice? 5

    Your total is $22.75
    Bye! See you soon.
    It was a pleasure to serve you!

    What is next?
    A modified Menu:
    1. Start the company’s initial state. That includes inventory with the cost associated with the purchases of the products. This feature enables the user to print the table below with the current inventory.
    NOTE: display all information in well-aligned columns. Use “printf”.

    1. Updates to the products, quantities, cost and the sale price.
    2. Closing of the business cycle by producing a report with all needed information.
    3. If you need more information from the client, add the questions to your list.
    4. Test your implementation with the client’s data.
    5. Let your client use your implementation.
    6. Make changes to your implementation based on your client’s comments and suggestions.

    Check edmodo for the due dates. WARNING: there are no soft due dates for this project. All due dates are hard and penalties will be applied.

    Find below some basic raw data to start with but it is not limited to.

    This menu will be used by the manager/owner/business operator

    Drinks 
             Quantity Available  Cost/case(45) $  Sale Price $
    1. Sunkist            45            16         1.25
    2. Coca Cola          45            18         1.25
    3. Brisk              45            17         1.25
    5. Sprite             45            17         1.25
    6. Ginger Ale         45            21         1.25
    7. Dr. Pepper         45            20         1.25
    8. Capri Sun          45            15         1.25
    9. Water              45            22         1.00
    
    Snacks 
             Quantity Available  Cost/case(45) $  Sale Price $
    1. Chips              45            25         0.75          
    2. Pop corn           45            22         0.75         
    3. Pop Corners        45            22         0.75     
    4. Veggie Sticks      45            21         0.75     
    5. Rice Krispies      45            20         0.50     
    6. Cookies            45            36         0.75         
    7. Granola Bars       45            40         0.50 
    8. Fruit Snacks       45            28         0.50 
    9. Snack Bars         45            41         0.50
    
    

    NOTE: Keep all this information as raw data in a text file.
    Raw data text file should look like this:
    snacks
    Chips,45,25,0.75
    Popcorn,45,22,0.75
    Pop Corners,45,22,0.75
    Cheeze it,45,18,0.75
    Gold Fish,45,18,0.75
    Oreo Cookies,45,30,0.75
    Fruit Snack,45,15,0.25
    Trail Mix,45,22,0.50
    Nutrigrain,45,31,0.50
    Peanut Bar,45,16,0.50
    drinks
    Coke,45,18,1.25
    Sprite,45,17,1.25
    Sunkist,45,16,1.25
    Brisk,45,17,1.25
    Ginger Ale,45,21,1.25
    Water,45,22,1.00
    Capri Sun,45,15,0.75
    else
    Ice cream,45,20,1.00
    Klondike Bars,45,15,1.25
    Italian Ice,45,10,1.25
    Ice pop,45,16,0.25
    end

    Warning: NO SPACES should be used to separate the data fields and the commas.

    I attached two files with java code to read and write text files. However, there are other options you can use.

    Q. What is the public interface of a class?
    A. The public interface of a class is a document with the name of each method, the description of the method, and the method’s pre-conditions and post-conditions.

    This menu could be typical for a menu for purchasing snacks and drinks

    Drinks 
                     Sale Price $
    1. Sunkist            1.25
    2. Coca Cola          1.25
    3. Brisk              1.25
    5. Sprite             1.25
    6. Ginger Ale         1.25
    7. Dr. Pepper         1.25
    8. Capri Sun          1.25
    9. Water              1.00
    
    Snacks 
                      Sale Price $
    1. Chips              0.75          
    2. Pop corn           0.75         
    3. Pop Corners        0.75     
    4. Veggie Sticks      0.75     
    5. Rice Krispies      0.50     
    6. Cookies            0.75         
    7. Granola Bars       0.50 
    8. Fruit Snacks       0.50 
    9. Snack Bars         0.50
    
    
    WriteToTxtFile

    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    // http://www.homeandlearn.co.uk/java/write_to_textfile.html
    /**
     * Write a description of class WriteToTxtFile here.
     * 
     * @author (your name) 
     * @version (a version number or a date)
     */
    public class WriteToTxtFile
    {
        public static void main(String [] args)
        {
            String myFile = "RawData.txt";
            try{
                FileWriter write = new FileWriter( myFile);
                PrintWriter print_line = new PrintWriter(write);
                print_line.printf("%s" + "%n", "Testing write to a file");
               
            print_line.close();
            }
            catch (IOException e) { System.out.println("It doesn't work");
            
            
            }
        }
    }
    
    

    [collapse]
    ScannerReadFile

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
     
    public class ScannerReadFile {
     
        public static void main(String[] args) {
     
            // Location of file to read
            File file = new File("data.txt");
     
            try {
     
                Scanner scanner = new Scanner(file);
     
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
                scanner.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
     
        }
    }
    
    
    

    [collapse]

    Standard Libraries
    printf short version
    printf resource

    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 4: Be Rational

    Chapter 4 Programming Assignment 7
    Write an application, RationalOperations_YI.java that lets the user add, subtract, multiply, or divide two fractions. Use the Rational class in your implementation. Implement the driver class to test all operations. Have a loop prompting the user for operators and operands.

    Screen Shot 2014-10-01 at 12.48.04 PM

    //********************************************************************
    //  RationalNumbers.java       Author: Lewis/Loftus/Cocking
    //  BeRational Assignment: change this driver so the user can input Rational
    //  numbers and selects the operations
    //  Prompt the user for the rational RationalNumbers
    //  Prompt the user for the operations
    //  Driver to exercise the use of multiple Rational objects.
    //********************************************************************
    
    public class RationalNumbers
    {
       //-----------------------------------------------------------------
       //  Creates some rational number objects and performs various
       //  operations on them.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {     
          Rational r1 = new Rational (6, 8);
          Rational r2 = new Rational (1, 3);
          Rational r3, r4, r5, r6, r7;
    
          System.out.println ("First rational number: " + r1);
          System.out.println ("Second rational number: " + r2);
    
          if (r1.equals(r2))
             System.out.println ("r1 and r2 are equal.");
          else
             System.out.println ("r1 and r2 are NOT equal.");
    
          r3 = r1.reciprocal();
          System.out.println ("The reciprocal of r1 is: " + r3);
    
          r4 = r1.add(r2);
          r5 = r1.subtract(r2);
          r6 = r1.multiply(r2);
          r7 = r1.divide(r2);
    
          System.out.println ("r1 + r2: " + r4);
          System.out.println ("r1 - r2: " + r5);
          System.out.println ("r1 * r2: " + r6);
          System.out.println ("r1 / r2: " + r7);
       }
    }
    
    

    Chapter 4 Programming Assignment 8
    Modify the Student class (Listing 4.13) with the following changes:

    a. Each student object also contains the scores for three tests.

    b. Provide a constructor that sets all instance values based on parameter values. 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. 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.