Category Archives: Lesson

Input/Output: Graphics: Simple Bar Graph

Screen Shot 2014-12-07 at 12.13.44 PM


Looking at the printf method
A printf format reference page (cheat sheet)

// This class shows how to initialize an array 
// How to use the printf output formatting method
public class InitPrintfArray 
{
   public static void main( String[] args )
   {
      // initializing the array when it is created
      int[] arrayA = { 87,56,78,99,102 };

      System.out.printf( "%s%7s\n", "Index", "Value" ); // column headings
   
      // output each array element's value 
      for ( int i = 0; i < arrayA.length; i++ )
         System.out.printf( "%5d%5d\n", i, arrayA[ i ] );
   } // end main
} // end class InitPrintfArray

A "simplified" version of a bar chart by using the elements of an array as counters

// Bar graph printing program.

public class BarGraph 
{
   public static void main( String[] args )
   {
      int[] arrayA = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };

      System.out.println( "Grade distribution:" ); 

      // for each array element, output a bar of the chart
      for ( int i = 0; i < arrayA.length; i++ ) 
      {
         // output bar label ( "00-09: ", ..., "90-99: ", "100: " )
         if ( i == 10 )
            System.out.printf( "%5d: ", 100 ); 
         else
            System.out.printf( "%02d-%02d: ", 
               i * 10, i * 10 + 9  ); 
 
         // print bar of asterisks
         for ( int stars = 0; stars < arrayA[ i ]; stars++ )
            System.out.print( "*" );

         System.out.println(); // start a new line of output
      } // end outer for
   } // end main
} // end class BarGraph

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Claswork/Homework:
Tracing 101: Trace the i, arrayA[i], and the output as the inner and outer loops traverse arrayA.

OOD: First Video from BlueJ

Classwork:
Chapter 1: VN 1.1 Introduction to key concepts
Take video notes.

Chapter 1: VN 1.2 Creating and using objects within BlueJ

Chapter 1: VN 1.3 methods and parameters

Assignment:

Using BlueJ’s video notes and source files on edmodo.com, create a new picture where there are more than one person in different locations, a house, a sun and grass.

Screen Shot 2015-01-13 at 10.07.43 AM house

OOD – Java and BlueJ Videos


OOD – Refresher
Java Video Tutorial 7


Chapter 3: VN 3.1 Fields of class types


Chapter 3: VN 3.2 Constructors and field initialization


Chapter 3: VN 3.3 Solving the 12-hour clock exercise

Look into edmodo.com for assignments and due date

Homework:
Watch this video:

If you are moving ahead:
Screen Shot 2015-02-02 at 10.03.46 AM

Use these libraries, download StdIn.java, StdOut.java, StdDraw.java, and StdAudio.java
Look at Standard output and input.
Redirection and piping.
Standard drawing.
Standard audio.
Graphical user interfaces.
Look at exercises 1 through 9 and work on exercise 10. Submit it to edmodo.com.

OOD Challenge Exercise

Chapter 1: VN 1.4 Solving a challenge exercise

Exercise 1:
Add a sunset to the single-sun version of Picture. That is: make the sun go
down slowly. Remember: The circle has a method slowMoveVertical
that you can use to do this.

Exercise 2: If you added your sunset to the end of the draw
method (so that the sun goes down automatically when the picture is
drawn), change this now. We now want the sunset in a separate method,
so that we can call draw and see the picture with the sun up, and then
call sunset (a separate method!) to make the sun go down.

You will find this code:
private Square wall;

private Square window;

private Triangle roof;

private Circle sun;

You need to add a line here for the second sun,

For example: private Circle sun2;

Then write the appropriate code for creating the second sun.

Exercise 3: Close the picture project, and open the lab-classes project.
This project is a simplified part of a student database designed to keep track of students in laboratory classes and to print class lists.
Create an object of class Student. You will notice that this time you
are not only prompted for a name of the instance, but also for some
other parameters. Fill them in before clicking Ok. (Remember that
parameters of type String must be written in double-quotes.)

OOD A Class Anatomy

OOD1
OOD2
OOD4
OOD5
OOD6
OOD7
OOD8
OOD9
OOD10
OOD11
OOD12

An ADT: Greeter

public class Greeter
{
   public String sayHello()
   {
      String message = "Hello, World!";
      return message;
   }
}

The tester class also called the driver:

public class GreeterTest
{
   public static void main(String[] args)
   {
      Greeter worldGreeter = new Greeter();
      System.out.println(worldGreeter.sayHello());
   }
}

An ADT: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      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)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

The driver class:

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

Assignments:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD – Quick Intro Summary


Concepts and terms to know well

A class is like:

  • a category or type
  • a blue print
  • a factory
  • a template

A class defines how “objects” or “instances” should be created and maintained.

The “data fields” or “instance fields” define the state of the object.

The “methods” or “behaviors” manipulate the “data fields” or “instance fields” to ensure consistent and proper handling.

If you notice, the instance fields are private. This fact and the use of methods to handle the instance fields promotes ENCAPSULATION.

Unprotected data

Encapsulation

OOD – SavingsAccount

What to turn in when you submit your work in edmodo.com:
* a. Copy and paste both programs
* b. Attach both files
* c. Output should be included in your tester/driver class as a comment
* d. Test all your code: Think of data that will force execution of all the lines of code.

Classwork:
Write a class SavingsAccount_YI that is similar to the BankAccount class, except that it has an added instance variable interest. Supply a constructor that sets both the initial balance and the interest rate. Supply a method addInterest (with no explicit parameter) that adds interest to the account. Write a tester/driver program that constructs a savings account with an initial balance of $1,000 and interest rate 10%. Then apply the addInterest method five times and print the resulting balance.

bank

OOD: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      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)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.

  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”

  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.

  4. Add a method

void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD: Pre conditions – Person

bug report
xkcd
Assignments:
1. Enhance the BetterBankAccount_YI class by adding preconditions
For the constructor: require the amount parameter to be at least zero
For the deposit method: require the amount parameter to be at least zero
For the withdraw method: the amount to be a value between 0 and the current balance

Driver: Write enough code in the tester class to invoke (call) all the methods.
Atm machines.

  1. Write a class Person with the following specifications:

a. Constructor: it takes a name as a string, a second string argument that describes what member of the family it is and, a third string describing the member activity to create a short story. You can make any changes you feel is necessary to accomplish this.

b. Mutator Method: setAge(int anAge). It prompts the user for age and updates the class instance field.

c. Mutator Method: setWhatIamDoing(String doing). It prompts the user and updates the class instance field currentActivity. Keep the number of activities low so it doesn’t become too lengthly.

d. Accessor Method: getWhatIamDoing(). It displays the currentActivity.

Tester class: MyFamilyDriver.java

despicableme2

Create or “instantiate” 4 persons, a mother, a father, a son or a daughter and a friend.
Simulate the following set of events:
The mother keeps milk in the refrigerator.
The father keeps juice in the refrigerator.
The son keeps a can of soda in the refrigerator.
The friend is thirsty and wants to drink something.

This is a story about “encapsulation” so your ending must reflect this concept. Be creative and use your imagination. The lines above is only an example. Do not use it for your own story. You can add more methods and instance fields to the Person ADT so you can make the simulation work nicely.

Some java language help:
String a = “abc”;
String b = “abcdefg”;
System.out.println(b.contains(a)); // true