Title: Assignment Statements
1Assignment Statements
- Weve already seen these, here we briefly look at
some examples and then look at some variations
Area of a circle given radius area PI
radius radius // PI is a constant Volume of
a cube volume length length
length Number of seconds in x years seconds
x 365 24 60 60 // whats wrong with
the above example? Convert F to C celcius
(5.0 / 9) (fahrenheit 32) celcius
((double) 5) / 9 (fahrenheit 32) Determining
change (assume amount in cents as in 142
cents) numQuarters amount 25 amount
amount numQuarters 25 numDimes amount
10 amount amount numDimes 10 numNickels
amount 5 amount amount numNickels
5 numPennies amount
2Variations
- Notice in the last example, we used statements
like - amount amount numQuarters 25
- We can replace the above code using a Java
shortcut operator - amount numQuarters 25 (note, there is
no space between and ) - The general form is x op change to replace x
x op change - x x 25 ? x 25
- x x y z / q ? x y z / q
- op can be any of , -, , /,
- The prefix/postfix increment/decrement lets us
swap x 1 or x x 1 with - these x x-- x --x
- The incr/decr can occur inside of other
expressions as in - y 5 x // y 5 x is computed first,
followed by x x 1 - if x 3, then when the statement is done, y 15
and x 4 - y 5 x // x x 1 is computed first
and then y 5 x with the new x - if x 3, then when the statement is done, y 20
and x 4 - These variations are commonly used with loops, so
we will explore these ideas in more detail later
3Control Statements
All instructions in a program execute
sequentially (one after the other) unless you use
control statements to alter the flow Two basic
forms are loops and selections
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
?
4Selection
- 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 - The decision is based on a boolean condition,
often of the form x op y where op is a relational
operator - 6 relational operators lt, lt, gt, gt, (equal
to), and ! (not equal to) - The values tested must be int, float, double or
char, not String - Weve already covered the if and if-else
statement, here we look at more details
5Comparing Strings
- We cant compare two Strings by using if(a b)
even though this seems like it should work - instead, the String class gives us comparison
methods - equals
- equalsIgnoreCase
- compareTo
- equals and equalsIgnoreCase return a true or
false, so they can be directly used in a
condition as in - if(firstName.equals(Frank))
- or if(firstName.equalsIgnoreCase(frank))
- compareTo returns an int value, negative if the
String is less than the String in ( ), 0 if they
are equal, and positive if the String is greater
than the String in ( ) - if(firstName.compareTo(Frank) lt 0)
System.out.println(your name comes first)
6Nested 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
7Grade 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?
8Another 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
9Switch, Break and Default
- Once a match occurs and the statements are
executed, we may want to get out of the switch
statement - we can do that by using break after our
statements list - 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
- 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 - The switch statement compares a variable against
a list of values and if it matches, it executes
the associated set of instructions and continues
on to the next list of values
switch (var) case val1 stmt stmt
case val2 stmt stmt
10Switch 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
11Compound Conditions
- Recall the code to the right, what is wrong with
it? - There is improper logic
- We need to replace this condition with a compound
condition - test 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 logic operators - There are 3 forms of logic operators used in Java
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
Notice the entire compound condition is placed
inside of ( ) marks
And (denoted as ) true only if all conditions
are true Or (denoted as ) true if any
condition is true Not (denoted as !) condition
is inverted (false ? true, true ? false)
12Conditional 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 single assignment statements that both
assign to the same variable - The conditional operator returns a value which
can be used as the right side expression of an
assignment - Its form is
- (condition) ? statement1 statement2
- If the condition is true, statement1 is computed
and returned, otherwise statement2 is computed
and returned - Example
- (total gt MAX) ? total 1 total 2
- This returns total 1 if the condition is true,
total 2 otherwise
13Example 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)
14Repetition
- 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
- We will cover while loops now and do and for
loops tomorrow
15The 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
16Example
- 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 output 1 2 4 8 16 32 64
524288
17Loop Termination
- There are several ways to terminate the loop
- which occurs when the condition is no longer true
- Computation value wait until the loop has
computed a certain upper (or lower) limit - this is how the prior loop worked
- Sentinel value input a value and enter the loop
as long as that value is not our sentinel - as an example, we might want to have the user
input a list of numbers to compute their average
we will use a negative number as our sentinel
value - our condition might read while(userNumber gt 0)
- User prompt after each loop iteration, ask the
user should we do this again or not? - our condition might read while(userAnswer ! N)
or while(userAnswer Y)
18Sum/Sentinel 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?
19A 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
20Computing 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!