Count or Accumulate?
Up ] Computing Fundamentals ] Program Design ] Object Oriented Design ] IBM vs. Mac (Humour) ] Search ] [ Translate ]
 

Count

How many cheques were printed?

To answer a question of this kind, we would use the counting design pattern.

or

Accumulate ?

What is the total net pay?

To answer a question of this kind, we would use an accumulating design pattern.

 

Counting Design Pattern

  1. Java has four different integer types, but we will standardize on int

    define an integer counter.
     
  2. initialize the counter.
    (i.e. explicitly give the counter a starting value.)
     
  3. increment the counter.
     
  4. use the resulting counter.

Example

// define counter
   int nCheques;
 
// initialize counter
   nCheques = 0;
 
// increment counter (add 1 to nCheques)
   nCheques = nCheques + 1;
 
// use counter
   System.out.println("Number of cheques printed: " + nCheques);

In the example, nCheques = nCheques + 1; accomplishes the counting.

 

Accumulating Design Pattern

What is the total net pay?  To answer a question of this kind, we would use an accumulating  design pattern:

  1. define an integer or a real accumulator (in Java, usually int or double), as appropriate.
     
  2. initialize the accumulator.
     
  3. increment the accumulator.
     
  4. use the resulting accumulator.

Example

// define accumulator
   double totalNetPay;
 
// initialize accumulator
   totalNetPay = 0.00;
 
// increment accumulator (add netPay to totalNetPay)
   totalNetPay = totalNetPay + netPay;
 
// use accumulator
   System.out.println("total net pay: " + totalNetPay);

Q  Where, in a Java program, should each of these processes appear?

a. define
b. initialize
c. increment
d. use

Special Java Operators

Counting (Incrementing)

An alternative to using:

nCheques = nCheques + 1;

is:

nCheques++;

Counting (Decrementing)

Similarly, the -- operator may be used to decrement.

 

Accumulating

An alternative to using:

totalNetPay = totalNetPay + netPay;

is:

totalNetPay += netPay;

Remember contractions from English?  (For example, can't is a contraction of cannot.)  Think of += as a contraction. 

The assignment operator contractions are:

  Assignment Statement    Alternative 
a = a / b; a /= b;
a = a * b; a *= b;
a = a % b; a %= b;
a = a + b; a += b;
a = a - b; a -= b;
 

[ Top of Page ] Up ] Computing Fundamentals ] Program Design ] Object Oriented Design ] IBM vs. Mac (Humour) ] Search ] [ Home ]
2000-2010, Peter Gehbauer PhD