Lecture 3: Control Structures (Selection, Repetition)

What You Will Learn Today

  1. Use selection structures (if, switch).
  2. Use repetition structures (for, while, do..while).
  3. Avoid common errors, use quality tips and productivity hints.
  4. Apply Boolean algebra and De Morgan's law.
  5. Use algorithms, pseudocode and flowcharting.
  6. Document programs with Javadoc.
  7. Get input from the keyboard using the Keyboard class.

Selection Structures

If Statement

Switch Statement

Switch Example

switch (digit)
{
   case 1: number = "one"; break;
   case 2: number = "two"; break;
   case 3: number = "three"; break;
   default: number = "error"; break;
}

Repetition Structures

For Statement

While Statement

Do..While Statement

Break, Continue and Goto

Common Errors

Quality Tips

Productivity Hints

Boolean Algebra and De Morgan's Law

Explain the use of this table and the patterns you see in it. Reproduce it without memorizing, simply by using logic.

A B A&&B A||B !A !B !(A&&B) !A||!B !(A||B) !A&&!B
false false false false true true true true true true
false true false true true false true true false false
true false false true false true true true false false
true true true true false false false false false false

Algorithms, Pseudocode and Flowcharting

Flowchart: Code-Compile-Test CycleFlowcharting

Steps for Solving Programming Problems

  1. Define the problem: What should the program do? What are the requirements? Who are the users?
  2. Design the interface: What objects and methods are needed? What are the inputs (parameters) and outputs (return values)?
  3. Design the internals: What algorithms and private variables should each method use?
  4. Code the solution: translate pseudocode into Java code and type into an editor.
  5. Compile the code to produce byte code.
  6. Test the code: run the program and check its response to different inputs (valid, boundary, invalid).

Pseudocode: Code-Compile-Test Cycle (Steps 4-6)

begin
   do
      do
         edit program
         compile program
      while there are compiler errors
      test program
   while there are run-time errors
end

Documenting with Javadoc

Example of a Javadoc Comment

/**
   Withdraws money from the bank account. Increments the transaction count.
   @param amount the amount to withdraw
   @return the balance after the withdrawal
   @throws IllegalArgumentException if the balance is not sufficient
*/
public double withdraw(double amount)
{
   ...
   return balance;
}

Generating Documentation with Javadoc

Getting Input Using the Keyboard Class

To Do After Class