Control Statements - PowerPoint PPT Presentation

1 / 59
About This Presentation
Title:

Control Statements

Description:

Comparing Floats ... if num1 num2, then we compare num1 and num3, to see which is smaller, if num1 ... Compare variable with val1, val2, ... and pick which ... – PowerPoint PPT presentation

Number of Views:142
Avg rating:3.0/5.0
Slides: 60
Provided by: xme
Category:

less

Transcript and Presenter's Notes

Title: Control Statements


1
Control Statements
  • There are generally three types of executable
    instructions in a program
  • Assignment statements
  • Input/output statements
  • Control statements
  • In a program, all instructions are executed
    linearly or sequentially
  • Unless a control statement alters the flow of the
    program
  • There are 3 types of control statements
  • Selection
  • Repetition (also called iteration or loops)
  • Procedure, Function or Subroutine calls

2
Branching Behavior
Sequential instruction Branching
instruction Sequential instruction Sequential
instruction Branching instruction Sequential
instruction Sequential instruction Sequential
instruction Branching instruction Sequential
instruction
Ordinarily, the program is executed by following
each sequential instruction in order A
control statement causes a branch to a new
location Branches may be used to select between
instructions, to skip over instructions, or
to repeat instructions
?
3
Selection
  • Selection statements are used to skip an
    instruction or to choose among a set of
    instructions
  • The selection is based on a boolean evaluation
  • Recall that booleans evaluate to true or false
  • If true, do the statement(s), if false, skip the
    statement(s)
  • The boolean evaluation can be based on a boolean
    variable but we will more commonly use a boolean
    expression
  • In this way, given 1 or more statements, the
    boolean expression is used to determine which one
    to select and execute

4
Boolean Expressions
  • A boolean expression is a set of code that, when
    evaluated, returns the value of true or false
  • Boolean expressions often use relational
    operators (e.g., lt, gt, ) to test the value of a
    variable or to compare two or more variables
  • Example x gt y returns true if the value in x is
    greater than the value in y, false otherwise
  • There are 6 relational operators
  • lt less than
  • gt greater than
  • equal to
  • notice it is not the same as used in
    assignment statements
  • ! not equal to
  • lt less than or equal to
  • gt greater than or equal to
  • Variables and values tested using relational
    operators can be of numeric types or char types,
    we will also see ways to compare String types

5
The if Statement
  • A common form of selection statement is the if
    statement
  • In the if statement, a condition is tested, and
    if it evaluates to true
  • then the statement which follows is executed,
    otherwise the
  • statement which follows is skipped

6
Examples
if (total gt amount) total total (amount
1) if (sex m) pay pay 500 if
(age gt 21) System.out.println("Ok, you can
drink") if (sunny) System.out.println("Wear
your sunglasses!") if (rainy)
System.out.println("Take an umbrella") if (x gt
y) x x 5 y
sex is a character sunny and rainy
are boolean variables
7
A Few Comments
  • Notice that the if statement must be preceded by
    the word if (not If or IF)
  • Also notice that the boolean condition must be
    placed within ( )
  • The condition itself is not followed by a
  • if (x gt y) x y 1
  • the statement to be executed if (x gt y) is
    not x y 1
  • x y 1 will be executed automatically be
    careful when writing your selection statements
  • We may couple the if statements with an else
    clause
  • in case there is an action to perform if the
    condition is false
  • this is known as an if-else statement (or
    if-then-else)

8
if-else statement
  • Used if there are two possibilities
  • For instance, if you want to calculate someones
    pay, there are two formulas, one for normal pay
    and another for overtime pay
  • Example to the right
  • Note that the if-else statement has two separate
    statements, one following the condition, one
    following the word else
  • Neither the condition nor else have a after
    it, the follows the statement
  • We refer to the statements as they if clause
    and the else clause

if (hours lt 40) pay hours wages else
pay 40 wages (hours 40)
wages 1.5
9
More Examples
if (score gt 60) grade P else grade
F if (number gt 0) sqt
Math.sqrt(number) else System.out.println("Ca
nt take the square root of a negative
number!") if (number 0)
System.out.println("Cant take reciprocal of
0") else rec 1.0 / (float) number if
(age gt 21) canGamble true else
canGamble false
Use if-else to decide what value should be
assigned a variable Use if-else to decide if an
operation could/should be performed
10
Comparing Floats
  • As a word of caution, comparing int and char
    types is straightforward but comparing two floats
    or doubles is tricky
  • if (a b) if a and b are floats, then (a
    b) is only true if they are precisely equal
  • Recall that float and double have a lot of
    precision and any two values may not be precisely
    equal
  • A solution is to do the following
  • if (Math.abs(a b) lt DELTA) where DELTA is a
    predefined limit for how closely together two
    floats or doubles need to be to be considered
    equal
  • for instance DELTA might be 0.001
  • the above statement says that we should consider
    a and b to be equal if the difference between
    them is less than 0.001

11
Block Statements
  • Notice that in all of our previous examples, the
    statement in the if clause and the else clause
    consisted of a single instruction
  • What if we needed to accomplish more than one
    instruction in an if or else clause?
  • We use block statements
  • A block is a sequence of statements that is
    treated like a single statement when placed in an
    if or else clause
  • Blocks are denoted by symbols
  • is the beginning of a block, is the ending of
    a block
  • Blocks will be used often in our Java programs

12
Example
If (temperature gt 80)
System.out.print("Wear shorts and t-shirt ")
effectiveTemp temperature HEATINDEX
humidity System.out.println("because it
is " effectiveTemp " degrees today")
Else System.out.println("It is not hot
today, the temperature is " temperature) The
if-clause has 3 instructions, so we place them in
a block If we didnt use a block, then we would
get a syntax error because the compiler would
get confused when it reached the else since it
did not immediately follow the if-clause
13
Nested Statements
  • A further problem arises if you have more than 2
    possible choices for a selection
  • For example, imagine that you want to assign a
    letter grade based on the students class
    average
  • 90 100 A
  • 80 89 B
  • 70 79 C
  • 60 69 D
  • 0 59 F
  • Can we do this with an if statement or an
    if-else? No
  • We could solve this with 5 if statements, or with
    a nested if-else statement
  • Nesting means that we have an if statement or an
    if-else statement as the statement inside of the
    if-clause or the else-clause or both

14
Grade Example
if (average gt 90) grade A else if
(average gt 80) grade B else if
(average gt 70) grade C else if
(average gt 60) grade D else grade
F if (average gt 90) grade A if
(average gt 80) grade B if (average gt 70)
grade C if (average gt 60) grade D if
(average gt 0) grade F
Nested approach Note indentation is not
needed, its there for program readability Altern
ate approach what is Wrong with this code? If
you have a 75, what is Your grade going to be?
We could solve this problem by reordering the if
statements in the opposite order, but the new
code would be inefficient why?
15
Another Example
import javax.swing. public class MinOfThree
public static void main(String args)
int num1, num2, num3, min 0
num1 Integer.parseInt (JOptionPane.showInputDi
alog (null, Enter a number)) num2
Integer.parseInt (JOptionPane.showInputDialog
(null, Enter a second number))
num3 Integer.parseInt (JOptionPane.showInputDi
alog (null, Enter a third number))
if (num1 lt num2) if (num1 lt num3)
min num1 else
min num3 else
if (num2 lt num3) min
num2 else min
num3 System.out.println("Minimum
value is " min)
Notice the logic here, if num1 lt num2,
then we compare num1 and num3, to see which
is smaller, if num1 lt num3 then num1 is
smallest (we already know num1is smaller than
num2) if num1 is not less than num2,
we compare num2 and num3
16
The Switch Statement
  • An alternate approach to using the nested if-else
    structure is an instruction called switch
  • We will use the switch statement if we are
    testing a single variable against a list of
    values
  • Structure
  • switch (variable) case val1
    statement1 case val2 statement2 cas
    e val3 statement3 case vallast
    statementlast default
    defaultstatement

Compare variable with val1, val2, and pick
which statement to execute based on which value
the variable matches
17
Break and Default
  • There is a problem with the Switch statement that
    is not obvious
  • If the variable matches a case, the statement is
    executed
  • BUT, the next case is examined anyways
  • There is a possibility that more than one case
    matches and so multiple statements could be
    executed
  • We include the reserved word break after each
    statement which forces the computer to transfer
    control to the instruction after the switch
    statement
  • Default is automatically executed so if no case
    matches and no instructions execute, no break is
    executed so that the default instruction is
    executed
  • The default can be thought of as the switchs
    else clause, automatically executed if no other
    statement executes

18
Switch Example
switch (grade) case A comment "gold
star" break case B comment
"silver star" break case C comment
"bronze star" break case D
comment "no star" break case F
comment "demerit" break default
comment "error, illegal letter grade! "
In this example, comment is a String which
is assigned a value based on the students letter
grade default is used as an error checking
mechanism here if reached, then the grade is an
illegal grade
19
Which Statement Should You Use?
  • If there is only one action, then use the if
    statement
  • If two actions, one if the condition is true, one
    if the condition is false, then use the if-else
    statement
  • If you have a series of possibilities, which
    should you use?
  • Switch statement if the possibility is based on a
    single variable and the variable is an integral
    data type (integer, character or a user defined
    type that is ordinal)
  • Otherwise, use the nested if-else statement
  • When it comes to selection, you have five
    possibilities
  • if statement
  • if-else statement
  • group of if statements
  • nested if-else statement
  • switch statement

20
Compound Conditions
  • Recall the code to the right, what is wrong with
    it?
  • There is improper logic, if average gt 80, then
    the boolean expressions for average gt 70,
    average gt 60 and average gt 0 are all true
  • We need to replace this condition with a compound
    condition that tests two things, if average gt
    current lower limit and also if average lt next
    lower limit
  • We create compound conditions by connecting them
    together with logical operators
  • One such operator is AND denoted in Java as

if (average gt 90) grade A if (average gt
80) grade B if (average gt 70) grade
C if (average gt 60) grade D if (average
gt 0) grade F
if (average gt 80 average lt 90) grade
B
21
Logic Operations
  • There are 6 logic operations
  • we will only use 3 in this course
  • AND true if all parts are true, use in
    Java
  • OR true if any parts are true, use in Java
  • NOT negates the boolean from true to false or
    from false to true, use ! in Java
  • XOR true if the two items differ
  • NAND NOT of AND
  • NOR NOT of OR
  • NOT is used on a single boolean variable or
    boolean expression
  • AND, OR, NAND and NOR can be applied to 2 or more
    boolean variables or boolean expressions
  • XOR is applied to exactly 2 boolean variables or
    boolean expressions
  • For Java, AND and OR are used on exactly 2
    boolean variables or boolean expressions

22
Truth Table for AND, OR, NOT
23
Compound Conditional Example
  • Assume done is a boolean variable, total is an
    integer, MAX is a constant
  • The compound conditional below might be used to
    perform an action as long as there are still
    actions to be performed (i.e., while we are not
    yet done) and also if the value of total is still
    less than the predefined MAX value

if (total lt MAX !found) System.out.println
("Processing")
The statement is only executed if both total lt
MAX and found is false
24
Other Boolean Operations
  • Aside from applying the relational operators
  • (lt, gt, , ! , lt , gt )
  • And the logical operators
  • , , !
  • There are other forms of boolean operations
  • Predefined instructions or class methods that
    return boolean values
  • One example is the String equals method
  • if (x.equals(y)) System.out.println("the two
    strings are the same")
  • We will see many other examples during this
    course as we introduce more and more classes

25
Increment/Decrement Operators
  • The syntax of Java is based on C
  • C contained a number of shortcut operators to
    make programming easier
  • These include the increment and decrement
    operators and --
  • count is the same as count count 1
  • These operators may go before or after the
    variable
  • -- a and a-- both perform a a 1
  • There is a slight difference between the prefix
    form and the postfix as we will discuss next

26
Inc/Dec in Assignment Statements
  • We are used to seeing assignment statements where
    only one variable gets a value as in
  • x (y 1) (z 1)
  • What if we wanted to increment y, decrement z,
    and then compute x? It would require 3
    statements
  • y y 1 z z 1 x y z
  • But using the increment and decrement operators,
    we can do this in one statement as
  • x y --z
  • What is the result of
  • x y z-- ?
  • Unfortunately, it is not the same!
  • The prefix operator performs the inc/dec first
  • The assignment is performed after any prefix
    operations
  • The postfix operator performs the assignment
    first follows by the inc/dec
  • The above statement is the same as
  • x y z y y 1 z z - 1

27
An Example
Assume sum 0, what is output from the following
statement? System.out.println(sum
" " sum " " sum " " sum--) 0 2 2
2 sum 0, so printing sum prints 0 and then
sum is incremented to 1, next we print sum, so
sum is first incremented to 2 and then it is
printed, next we print sum without incrementing
it, so 2 is again printed, and finally we print
sum -- so 2 is printed and then sum is
decremented to 1 What is the result of
System.out.println(sum " " sum) ?
28
Assignment Operators
  • A better name is a reassignment operator
  • In a statement like x x 5 we are reassigning
    the value of x to be 5 greater, or x5
  • In algebra, such a statement is nonsense, there
    is no way that x could ever equal x 5
  • But in programming, this is a common event, we
    want to increase (or decrease) a variable by some
    amount through a reassignment
  • Java gives us several shortcut assignment
    operators
  • - /
  • x 5
  • is equivalent to x x 5
  • see figure 3.8, page 129 for other forms
  • This even works with string concatenation as in
  • string1 string2
  • is equivalent to
  • string1 string1 string2 or
  • string1 string1.concat(string2)

29
Conditional Operator
  • There is one additional shortcut operator, this
    one can be used in place of an if-else statement
    as long as the if clause and else clause both
    contain a single statement
  • This statement returns a value, the result of
    the if clause or the else clause
  • Its form is
  • (condition) ? statement1 statement2
  • In which case, either the value computed in
    statement1 or the value computed in statement2 is
    returned
  • Example
  • (total gt MAX) ? total 1 total 2
  • This returns total 1 if the condition is true,
    total 2 otherwise

30
Using the Conditional Operator
  • We will use the conditional operator in an
    assignment statement so that the value returned
    is stored somewhere
  • We might use it to replace the following if-else
    statement with a single assignment statement

if (total gt MAX) total total 1 else
total total 2
total (total gt MAX) ? total 1 total 2
Another Example int larger (num1 gt num2) ?
num1 num2 Instead of if (num1 gt num2) larger
num1 else larger num2
31
Example Computing Grades
import javax.swing. public class Grades
public static void main(String args)
int test1, test2, test3, total float
average char letterGrade test1
Integer.parseInt(JOptionPane.
showInputDialog(null, Enter first test
score)) test2 Integer.parseInt(JOptionPane.
showInputDialog(null, Enter second test
score)) test1 Integer.parseInt(JOptionPane.
showInputDialog(null, Enter third test
score)) total (test1 gt 60 test2 gt 60
test3 gt 60) // compute total but ? test1
test2 test3 0 // only if student
has average (float) total / 3 // passed
all 3 exams if (average gt 90.0) letterGrade
A // otherwise total 0 else if
(average gt 80.0) letterGrade B
else if (average gt 70.0) letterGrade C
else if (average gt 60.0) letterGrade
D else letterGrade F System.out.pri
ntln("Students average is " average " for a
grade of " letterGrade)
32
Repetition
  • What happens if we want to do some action
    multiple times?
  • For instance, we want to compute multiple
    students grades?
  • We could run our grade program several times
  • But this is tiresome and also does not allow us
    to compute things like class averages or sort the
    scores or anything like that
  • We instead need instructions that allow code to
    be repeated thus repetition control statements
  • There are three forms of repetition statements in
    Java
  • While loops
  • Do loops
  • For loops

33
The While Statement
  • The while statement evaluates a condition
  • if that condition is true, the body of the while
    statement is executed and the process is repeated
  • If the condition is false, the rest of the
    statement is skipped and control continues with
    the next instruction after the while statement

34
Example
  • Lets write a loop that will compute the powers of
    2 that are less than 1000000
  • We start with a variable set equal to 1
  • We loop while that variable lt1000000
  • Inside the loop, we print the value of the
    variable and then multiply it by 2
  • Notice that since the loop body is more than a
    single statement, we enclose it in to make it
    a block

int value 1 while (value lt 1000000)
System.out.println(value) value
2 outputs 1 2 4 8 16 32 64
524288
35
Sentinel Values
  • In the prior example, we iterated until we
    reached an upper limit
  • We will often use While loops to repeat some
    action such as input some value, perform a
    calculation, output a result, repeat until the
    user is done
  • How do we know if the user is done?
  • We could ask the user or we could base the
    decision on the input value this is known as a
    sentinel value
  • Example input a list of integers until the user
    enters a negative number, and compute the sum of
    these numbers

36
Sum Example
int value, sum sum 0 value
Integer.parseInt(JOptionPane.showInputDialog
(null, Enter a positive integer, negative
number to quit)) while (value gt 0) sum
value value Integer.parseInt(JOptionPa
ne.showInputDialog (null, Enter next positive
integer, negative number to quit)) System.out
.println("The sum of the numbers you entered is
" sum)
Initialize sum before we enter the loop
value lt 0 is our sentinel for the loop
Notice that we repeated these Instructions why?
37
A slightly different version
int value, sum sum 0 value
Integer.parseInt(JOptionPane.showInputDialog
(null, Enter a positive integer, negative
number to quit)) while (value gt 0) sum
value System.out.println("The sum of the
numbers you entered is " sum)
Notice in this version we dont ask for the next
value this means that value never changes if
it never changes, then it is always the original
value, if that value was gt 0, it will always be
gt 0 and thus the loop will never stop this is
an infinite loop
38
Infinite Loops
  • Careless (and even careful) programmers will
    write infinite loops
  • This is a major problem when using the while loop
  • The basic idea behind the loop is to continue
    executing while a condition is true
  • If that condition is based on an input value,
    then the program must input a new value during
    each iteration so that the user can change the
    value to one that exits the loop
  • Otherwise, the value never changes and the loop
    never stops!
  • Exiting an infinite loop
  • if you suspect that your program is caught in an
    infinite loop, about your only recourse is to
    stop the program
  • Press control-C on the keyboard

39
Computing an Average
int number, count, sum float average sum
0 count 0 number Integer.parseInt(JOptionPan
e. showInputDialog(null, Enter a number, 0
to end)) while (number gt 0) sum
number count number
Integer.parseInt(JOptionPane.
showInputDialog(null, Enter a number, 0 to
end)) average (float) sum /
count System.out.print("The average of your "
count) System.out.println("numbers is "
average)
This program is similar to the sum program from
before, but we are also counting the number of
inputs using the count variable 0 (or any
negative number) is our sentinel
value Notice that average is not
formatted, our output might look messy!
40
Query-Controlled Loops
  • Rather than basing the condition of the loop on a
    number, we could also ask the user
  • We could modify our program from the previous
    slide
  • Our prompt changes to
  • answer JOptionPane.showInputDialog(null, Do
    you have another value to enter? (y/n)
    ).charAt(0)
  • Our condition changes to
  • while (answer y)
  • Notice that if the user inputs a Y we have a
    problem, so lets change our condition to be
  • while (answer y answer Y) or
  • while (answer ! n answer !N)

41
A String version
String answer answer JOptionPane.showInputDial
og(null, "Do you want to do this again?
") While(answer.equals.toUpperCase("YES"))

We convert the string to upper case
before comparing to YES
This resolves the problem of whether the user
responds with yes, YES, Yes or some other
derivation, but what if the user responds with
Y or Yea or some typo? We might
try While(answer.toUpperCase.charAt(0)
Y) compare only the upper case version of
the 0th character
42
Nested Loops
  • Just as we had nested if-else statements, we will
    often want to have nested loops
  • In this case, we nest loops when there are things
    we need to repeat repeatedly
  • We might want to create an averaging program that
    allows the user to enter multiple sets of numbers
  • The user inputs a set of numbers ending with a
    negative number, and the average is computed
  • The program asks the user if he/she wants to do
    another set, and if yes, the entire process is
    repeated
  • The outer loop will initialize the sum to 0 and
    then enter the inner loop
  • The inner loop will input a number, add it to the
    sum and increment count, asking for the next
    number
  • Upon exiting the inner loop, the outer loop
    calculates and outputs the average, and asks if
    the user wants to do another set or not
  • We can have as many nestings of loops as we want

43
Averaging Program with 2 loops
import javax.swing. public class Averager
public static void main(String args)
int num, sum, count String
answer answer
JOptionPane.showInputDialog(null, "Do you want
to average a set of numbers? (Y/N) ")
while (answer.charAt(0) Y
answer.charAt(0) y) num
Integer.parseInt(JOptionPane.showInputDialog(nul
l, Enter your first number ")
while (num gt 0)
sum num count
num Integer.parseInt(JOptionPane.showInputDia
log(null, Enter your next number, a negative
to end ")) if (count gt
0) average (float) sum / count else average
0.0f System.out.println("for
the " count " values entered ")
System.out.println(" the average is "
average) answer JOptionPane.showInputDialog(n
ull, "Do you want to average another set
of numbers? (Y/N) ")
System.out.println("Goodbye! ")
Outer Loop controlled by users
answer Inner Loop controlled by sentinel
value
44
The do Loop
  • The do loop is similar to the while loop but is a
    post-test loop, the while loop is a pre-test loop
  • The Do loop starts with the reserved word do
    followed by the loop body and then the reserved
    word while and the condition
  • The difference is the flow of control here, the
    condition is not evaluated until after the body
    of the loop executes

45
While vs. Do
  • The only difference between these two statements
    is when the condition is evaluated
  • While evaluated before executing the loop body
  • Do evaluated after executing the loop body
  • If you want to automatically execute the loop
    body at least once, use the Do loop
  • If you dont want to do the body if the condition
    is not true, use the While loop

46
Using Loops to Verify Input
  • Consider a situation where we want the user to
    input one of a set of values that constitute a
    legal input
  • What if the user enters an illegal input?
  • Example input a positive integer and take the
    square root
  • If x lt 0, we would get a run-time error when the
    sqrt operation is invoked!
  • A solution to this problem is to place the prompt
    and input statements inside a loop that only
    terminates once the user has entered the right
    value
  • We will use a do statement for this since we will
    want the user to input the value at least one time

x Integer.parseInt(JOptionPane.showInputDialog(n
ull, "Enter a positive integer ")) y
Math.sqrt((double) x)
do x Integer.parseInt(JOptionPane. showI
nputDialog(null, "Enter a positive integer
")) while (x lt 0) y
Math.sqrt((double) x)
47
for Loop
  • The While and Do statements are most commonly
    used when the condition is based on an input
    that is, the user will decide whether to execute
    the loop again or not
  • In another situation, we might have a limit on
    the number of times we want to execute the loop
    body then we will use the for loop
  • The for loop is sometimes referred to as a
    counting loop
  • it counts the number of iterations performed
  • We can make the for loop count from 1 to 10,
    from 1000 down to 1, from 0 to 100 skipping every
    other number,
  • In fact, the for loop provides so much
    flexibility that we can have it do the same thing
    that a while loop does

48
Structure of a For loop
Initialize the loop variable(s) Check the
condition if true, execute the body Perform
the increment which might alter the condition
49
For loop examples
  • Iterate 100 times
  • for(i0ilt100ii1) System.out.println(" "
    i)
  • Iterate from 1000 to 1
  • for(i1000igt0ii-1) System.out.println(" " i)
  • Iterate from a to b (a and b are ints)
  • for(jajltbj)
  • Iterate from 0 to 1000 by 2s
  • for(j0jlt1000j2)
  • Iterate from 0 to 1000, increasing the step size
    by 1 each time (e.g., 0, 1, 3, 6, 10, 15, 21, )
    (assume n is initialized to 1)
  • for(k0klt1000kn)

Historic note In early FORTRAN, all variables
floats (called real in FORTRAN) unless the
variable name started with a letter I through
N (I..N for integer) Thus, it was popular to
use i, j, k, , n for loop variables and we
continue to do the same today
50
Using the For loop
  • When having to perform some action a known number
    of times, we use the for loop instead of the
    while loop because it is easier
  • We dont have to do the initialization or
    incrementing, those are done for us!
  • Example print the square of each integer from 1
    to 25

for (value 1 value lt 25 value)
System.out.print(value " squared is "
value value)
value 1 while (value lt 25)
System.out.print(value " squared is "
value value) value value 1
51
Additional Loop Examples
  • Assume that str is a String, the following prints
    the characters of str backwards

If str hi there, then length is 8 although
the positions in the string are numbered 0
7. Starting at 7, going back to 0, print each
character
for (istr.length()-1igt0i--)
System.out.print(str.charAt(i)) System.out.printl
n()
  • And here is a variation of the averaging program
    ask the user how many items there are to
    average

x Integer.parseInt(JOptionPane.showInputDialog
(null, "How many numbers do you have to
enter? " )) for(i0iltxi) num
Integer.parseInt(JOptionPane.showInputDialog
(null, "Enter value " i ))
sum num average (float) sum / x

52
Nested For Loop Examples
  • If n 5, this outputs
  • 2 3 4 5
  • 4 6 8 10
  • 6 9 12 15
  • 8 12 16 20
  • 10 15 20 25
  • Notice that it doesnt
  • quite line up!

for(i0iltni) for(j0jltnj
System.out.print(" " ij)
System.out.println()
For(I0IltnI) for(j0jltI1j)
System.out.print("") System.out.println()

If n 5, this outputs
53
Some Odd For Loops
  • for(xJOptionPane.showInputDialog(null, "Again?
    ") !x.equals("no") xJOptionPane.showInputDialog
    (null, "Again? "))
  • What does this for loop do? It inputs a string
    from the user and if it is not no it executes
    the loop body before asking the user for another
    string
  • Essentially, this for loop is doing the same as
    our query controlled while loops from earlier
  • for(a0, b0 a gt c b gt d a, bb3)
  • Here, we have 2 loop variables, a and b
  • a is incremented by 1 and compared to c
  • b is incremented by 3 and compared to d
  • Keep looping if either a gt c or b gt d
  • We can get pretty bizarre with our for loops as
    needed
  • Hopefully we wont need to though!

54
Example Prime number
import javax.swing. public class
PrimeNumberComputer public static void
main(String args) int i, num,
limit boolean prime true num
Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter a number, I will see if it is
prime ")) for(i2iltnumi) if (num
i 0) prime false if (prime)
System.out.println(num " is a prime number.
") else System.out.println(num " is not
a prime number. ")
An improvement Change the for loop to
iterate from 2 to num/2 or even better
Change the for loop to a while loop Why
would this be an improvement?
if (num i 0) it means that num is divisible
by i, and since i ! 1 and i ! num, then num
has a divisor not equal to 1 or itself
55
Menu Driven Programs
  • We now have the proper tools to put together a
    menu driven program if we choose to
  • What is a menu driven program?
  • The user is able to select what the program
    should do from a menu
  • Repeat the following
  • The menu is displayed
  • The user selects a choice
  • If legal, the proper operation is performed, if
    illegal, an error message is displayed
  • Until the user selects the quit option
  • We will use a do loop to implement the repetition
  • We will use a switch statement to select the
    operation based on the users choice

56
Menu Driven Example
// assume num is an int variable, previously
input choice Integer.parseInt(JOptionPane.show
InputDialog(null, "Enter 1 for square, 2
for square root, 3 for prime ") " 4
for new number, 5 to quit ")) while (choice
! 5) switch (choice) case 1
System.out.println("Square is " num
num) break case 2 System.out.println("Squar
e root is " Math.sqrt((double) num)
break case 3 / place prime number code
here / break case 4 num
Integer.parseInt (JOptionPane.showInputDialog
(null, "Enter a new number ") break case 5
System.out.println("Thanks for using calculator
") break default
System.out.println("Incorrect choice, try again!
") choice Integer.parseInt(JOptionPane.showI
nputDialog(null, "Enter 1 for square, 2
for square root, 3 for prime ") " 4
for new number, 5 to quit "))
  • Consider a simple example
  • given an input value, the user can either have
    the program compute the numbers square, square
    root, if it is prime or not, input a new number,
    or quit

57
Example Counting vowels
import javax.swing.public class CountVowels
public static void main (String args)
int i, j, count String input,
vowels vowels new String("aeiou") count
0 System.out.println("Enter a string and I will
count the number of vowels") input
JOptionPane.showInputDialog(null, "Enter a string
") input input.toLowerCase() System.out.pri
ntln() for (i0 iltinput.length() i) for
(j0 jlt5 j) if (input.charAt(i)
vowels.charAt(j)) count System.out.println(inp
ut " has " count " vowels in it")
58
Example Rock-paper-scissors
import java.util.Randomimport
javax.swing.public class RockPaperScissorsGame
public static void main (String args)
Random generator new Random() int
computerNumber, computerWins, userWins,
game String again, computerAnswer, userAnswer,
win game 0 computerWins 0 userWins
0 do game userAnswer
JOptionPane.showInputDialog(null, "Enter
rock, paper or scissors " ).toLowerCase()
computerNumber generator.nextInt() 3
1 switch (computerNumber) case 1
computerAnswer "rock" break case 2
computerAnswer "paper" break case 3
computerAnswer "scissors" break
default System.out.println("Error, computer
generated illegal answer!")
59
if (userAnswer.equals(computerAnswer)) win
"tie" else if ((userAnswer.equals("rock"
) (computerAnswer.equals("scissors")))
(userAnswer.equals("paper")
(computerAnswer.equals("rock")))
(userAnswer.equals("scissors")
(ComputerAnswer.equals("paper"))))
win "user" else win
"computer" System.out.println("User chose
" userAnswer) System.out.println("Computer
chose " computerAnswer) System.out.println("W
inner is " win) System.out.println() if
(win.equals("user")) userWin else
if(win.equals("computer")) computerWin again
JOptionPane.showInputDialog(null, " Play
Again? " ) while (again.charAt(0) 'Y'
again.charAt(0) 'y')
System.out.println("Out of " games " games
played, ") System.out.println(" the user won "
userWin " games") System.out.println(" the
computer won " computerWin "
games") System.out.println() System.out.printl
n("Thanks for playing!")
Rock-paper-scissors cont.
Write a Comment
User Comments (0)
About PowerShow.com