Lecture 3: Control Structures
(Selection, Repetition)
What You Will Learn Today
- Use selection structures (if,
switch).
- Use repetition structures (for,
while, do..while).
- Avoid common errors, use quality tips and
productivity
hints.
- Apply Boolean algebra and De
Morgan's law.
- Use algorithms, pseudocode and flowcharting.
- Document programs with Javadoc.
- Get input from the keyboard using the
Keyboard class.
- Selection structures include if statement, selection
operator (see Lecture 2), and switch
statement.
- They test if a condition is true or false, make decisions and perform actions accordingly.
- They select zero or more statements to perform or expressions to
evaluate.
- They branch (move) to a location of zero or more statements.
If Statement
- The
if
statement has the form:
if (condition) statement1 [else statement2]
- Meaning: If condition is true, perform statement1. Otherwise
perform statement2. e.g.
if (gender == 'm') title = "Mr."; else title = "Ms.";
if
statements can be chained together to handle multiple cases.
e.g.
-
if (a == b) relation = "equal";
else if (a > b) relation = "greater than";
else if (a < b) relation = "less than";
- The
else
statement is optional; many if
statements do not use else
.
- A block statement is one or more statements { inside braces }
which can be used instead of a simple statement. e.g.
if (a > b) { temp = a; a = b; b = temp; } // swap values of a and b
using a temporary variable
- The
switch
statement has the form:
switch
(expression)
{
case constant1:
statements1
case
constant2: statements1
...
default: defaultStatements
}
- Meaning: The
switch
statement is equivalent to several
if-then-else
statements:
- If expression is equal to constant1, perform statements1
- else if expression is equal to constant2, perform
statements2 ...
- else perform defaultStatements
- The
switch
statement can be useful in reducing and
simplifying code where an expression has a large number of values.
- Often a
break
statement is used after each
case
. (Common error: forgetting the break
.)
- Generally avoid
switch
statements because they can be
difficult to debug.
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 include
for
,
while
and do..while
statements.
- They repeat a group of zero or more statements.
- They iterate or loop a certain number of times back to the line in the code
where the loop starts.
- Conditions like those for selection structures determine the number
of repetitions.
For Statement
- The
for
statement has the form:
for
(initExpression|variableDeclaration;
condition; updateExpressions)
statement
- The most common use has the form:
for
(int i = start; i <= end; i++)
statement
- e.g.
factorial = 1; for (int i = 1; i <= n; i++) factorial *=
i;
- e.g.
for (i = 1; i <= n; i++) { double interest = balance *
rate / 100; balance += interest; }
- The
while
statement has the form:
while
(condition)
statement
- Meaning: While the condition is true, execute the statement. The statement
may be executed zero or more times.
- e.g.
i = 1; factorial = 1; while (i <= n) factorial *= i++;
- e.g.
while (true) statement
// an infinite
loop; keeps executing statement forever
- The
do..while
statement has the form:
do
statement while (condition)
- Meaning: Execute the statement at least once, and continue executing while
the condition is true.
-
do..while
is often used to get multiple input values
from the user; it must get at least one user input, e.g.
do
{
input = console.readLine();
System.out.println("You entered: " + input);
}
while (input != null);
Break, Continue and Goto
break
causes termination of a loop or switch
continue
starts the next iteration of the loop
goto
goes to a numbered line (not used in Java; found
in older programming languages like C++ and Basic)
- unbalanced parentheses or braces (number of left and right parentheses or
braces should be equal)
- dangling else problem (when in doubt, use braces)
- unintended operator precedence (when in doubt, use parentheses)
- multiple relational operators
- confusing && and ||
- using the assignment operator
=
instead of ==
to test for equality
- testing floating point numbers for equality instead of near equality
- infinite loops (remember to increment/decrement inside the loop)
- off by 1 (starting with 1 vs. 0; using < vs. <=; use test cases)
- forgetting a semicolon, or too many semicolons
- line up braces {} horizontally or vertically (see switch example)
- use indentation to show loop structure including nested loops
- prepare test cases ahead of time
- avoid side effects and doing two things at once, such as both
assigning and testing variables inside loop conditions
- use loops for their intended purposes only
- do not use != to test the end of a range; use < or <= instead
- avoid
break
, continue
and
goto
because they make code that is hard to read and debug
- flowcharts are not often used today because of their nonlinear flow
- programming editor features (see Using Kate):
highlighting, line numbers, indenting, keyboard and shell shortcuts
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 |
- An algorithm is how to do something; a detailed sequence of actions
performed in order to accomplish a task.
- Algorithms can be represented using a natural language, programming
code, pseudocode, flowcharts, or other diagrams.
- Pseudocode is a set of instructions that look like both a
programming language e.g. Java and a natural language
e.g. English.
- A flowchart is a diagram that shows the flow of control in an
algorithm, including steps and decisions.
Flowcharting
- Circles show start and end points or states of the algorithm.
- Rectangles show steps or actions (e.g. a statement or block).
- Diamonds show decisions as True/False or Yes/No questions.
- Arrows show the flow of control.
Steps for Solving Programming Problems
- Define the problem: What should the program do? What are the
requirements? Who are the users?
- Design the interface: What objects and methods are needed? What are
the inputs (parameters) and outputs (return values)?
- Design the internals: What algorithms and private variables should
each method use?
- Code the solution: translate pseudocode into Java code and type
into an editor.
- Compile the code to produce byte code.
- 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
- A Javadoc documentation comment begins with
/**
and ends with
*/
on
otherwise blank lines.
- Every class and method should have a comment directly above it.
- The first line of the comment should be one sentence summarizing the class
or method.
- Other commonly used comments are noted with tags that begin with @,
e.g.
@author
name
- the person who created the class or interface
@param
parameter explanation
- a method parameter (use one
line for each parameter)
@return
explanation
- the return value of a method
@throws
exceptionType explanation
- an exception a method
may throw (one line for each)
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
- Javadoc is a tool that uses source code (.java files) to automatically
generate program documentation HTML format.
- Javadoc is part of the Java Software Developers Kit (SDK) which may need
to be installed on your computer.
- To create documentation for one file, type
javadoc filename.java
.
- To document all files in a directory, type
javadoc *.java
.
- To view the resulting documentation, open
index.html
in a web browser.
- The Keyboard class can be used
to simplify keyboard input.
- A subdirectory named cs1 must contain the Keyboard.class file.
import cs1.Keyboard;
// this line must appear in the source
code, at the top
- Keyboard methods you can use include
readString()
,
readInt()
, and readFloat()
.
- For a simple example of how to use the Keyboard class, see
KeyboardString.java.
To Do After Class