Author Archives: graceliana@gmail.com

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 – Software Life Cycle

Software Development Activities

Four basic development activities:

  • establishing the requirements
  • creating a design
  • implementing the design
  • testing

This sequence would be ideal but it almost never completely linear in reality.
They overlap and interact.

Software requirements specify what a program must accomplish: a document called a functional specification.

The client will often provide an initial set of requirements. However, these initial requirements are often incomplete, ambiguous, and perhaps even contradictory.

The software developer must work with the client to refine the requirements.

A software design indicates how a program will accomplish its requirements.

The design specifies the classes and objects needed in a program and defines how they interact. It also specifies the relationships among the classes.

During software design, alternatives need to be considered and explored. Often, the first attempt at a design is not the best solution.

Implementation is the process of writing the source code that will
 solve the problem.

Too many programmers focus on implementation exclusively when actually it should be the least creative of all development activities. The important decisions should be made when establishing the requirements and creating the design.

Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform.

Identifying classes and objects

A fundamental part of object-oriented software design is determining the classes that will contribute to the program. We have to carefully consider how we want to represent the various elements that make up the overall solution. These classes determine the objects that we will manage in the system.

When designing classes, objects are generally nouns.

The nouns in a problem description may indicate some of the classes and objects needed in a program.

A class represents a group of objects with similar behavior. A plural noun is an indication that your design might not be good.

Classes that represent objects should generally be given names that are singular nouns.

A class represents a single item from which we are free to create as many instances as we choose.

Another key decision is whether to represent something as an object or as a primitive attribute of another object.

We want to strike a good balance between classes that are too general and those that are too specific.

There might be additional classes to support the work necessary to get the job done.

Keep in mind that may be an old class that’s similar enough to serve as the basis for our new class.

The existing class may be part of the Java standard class library, part of a solution to a problem we’ve solved previously, or part of a library that can be bought from a third party, “Software Re-usability”.

Assigning responsibilities

Part of the process of identifying the classes needed in a program is the process of assigning responsibilities to each class. Each class represents an object with certain behaviors that are defined by the methods of the class. Any activity that the program must accomplish must be represented somewhere in the behaviors of the classes. That is, each class is responsible for carrying out certain activities, and those responsibilities must be assigned as part of designing a program.

Generally use verbs for the names of behaviors and the methods that accomplish them.

Sometimes it is challenging to determine which is the best class to carry out a particular responsibility. You could benefit from defining another class to shoulder the responsibility.

It’s not necessary in the early stages of a design to identify all the methods that a class will contain. It is often sufficient to assign primary responsibilities and consider how those responsibilities translate to particular methods.

Class and object relationships

The classes in a software system have various types of relationships to each other. Three of the more common relationships are dependency, aggregation, and inheritance.

Dependency relationships: a class “uses” another.
Class A uses class B, then one or more methods of class A invoke one or more methods of class B. If an invoked method is static, then A merely references B by name. If the invoked method is not static, then A must have access to a specific instance of class B in order to invoke the method. That is, A must have a reference to an object of class B.

dependency

UML notation distinguishes between object diagrams and class diagrams. In an object diagram the class names are underlined; in a class diagram the class names are not underlined. In a class diagram, you denote dependency by a dashed line with a shaped open arrow tip that points to the class that is dependent on. Figure 1 shows a class diagram indicating that the CashRegister class depends on the Coin class.

Note that the Coin class does not depend on the CashRegister class. Coins have no idea that they are being collected in cash registers, and they can carry out their work without ever calling any method in the CashRegister class.

coupling

Aggregation: the objects of one class contain objects of another, creating a “has-a” relationship.
When one class instantiates the objects of another, it is the basis of an aggregation relationship. The access can also be accomplished by passing one object to another as a method parameter.
The less dependent our classes are on each other, the less impact changes and errors will have on the system.

Inheritance: creates an “is-a” relationship between classes.

Assignment:

Design an application:

A computer-based system is to be implemented for an airport snack bar business, Goodies Co.
1. Define what the needs are.
2. Based on the previous, create a list of questions for your “client”.
3. Work with your partner to outline the different components to run the company.

vendingmachines

 

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

Programming Assignment 4.9
Design and implement a class called Building that represents a drawing of a building.
The parameters to the constructor should be the building’s width and height.
Each building should be colored black and have a few random windows colored yellow.
Create an application with StdDraw that draws a random skyline of buildings.
skyline

StdDraw library from PU

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