Title: Week 03 b
1Week 03 - b
- Control Structures
- Decisions
2Sample Programs Referenced(code located in
course folder)
- PigLatin
- ComputeTax
- RollTheDice
- MissingBreak
- Simple Calculator
- GUI Calculator
- DaysInMonth
- OrdinalSuffix
3Hint on ReadingGrade Counts for HW 3
- import javax.swing.
- public class GradeBreakdown extends Applet
- private int numA, numB, numC, numD, numF
- public void init()
- numA Integer.parseInt(
- JOptionPane.showInputDialog(
- "Number of A's?"))
- numB Integer.parseInt(
- JOptionPane.showInputDialog(
- "Number of B's?"))
- . . .
- // end of init method
- . . .
- // end of GradeBreakdown applet
4Control Structures
- Regulate flow of execution in a program or method
- Individual instructions combined into a single
logical unit with - One entry point
- One exit point
- 3 Types of Control Structures
- Sequence
- Selection
- Repetition (later)
5Sequence
- A compound statement group of statements
bracketed with curly braces -
- statement1
- statement2
-
- statementn
-
- Statements executed sequentially
- That's what we've been doing
6Selection
- A selection is made
- whether to execute a statement, or
- which of some alternative statements will be
executed - Makes possible program design in which some
statements may be skipped, and other statements
executed - Selection is based on some logical criteria
- if (bankBal lt 0)
- System.out.println( Deposit some money! )
- else
- System.out.println( Balance is bankBal )
7Flowcharts
balance lt 0
yes
no
display deposit
display balance
8if Statement
- Ensures that a statement is executed only when a
condition is true - Conditions typically involve comparison of
variables or quantities for equality or
inequality - Syntax
- if ( condition )
- statement
- Example
- if (age gt 18)
- out.println(Eligible to vote.)
9(No Transcript)
10if Statement with Optional else
- An if statement may have an optional else clause
that will only be executed when the condition is
false - Syntax
- if ( condition )
- statement
- else
- statement
- Example
- if (wages lt FICA_LIMIT)
- tax FICA_TAX_RATE wages
- else
- tax FICA_TAX_RATE FICA_LIMIT
11PigLatin "unionway ollegecay"BlueJ
- public class PigLatin // modified from
Koffman Wolz page 206 - private String word
- public PigLatin(String word)
- this.word word
- // end of PigLatin constructor
- private boolean firstLetterVowel()
- final String VOWELS "aeiouyAEIOUY"
- char first word.charAt(0)
- return (VOWELS.indexOf(first) gt -1)
- // end of firstLetterVowel method
- public String translateWord()
- if (firstLetterVowel()) return word "way"
- else return word.substring(1)
word.charAt(0) "ay" - // end of translateWord method
- public String toString()
- return word
- // end of toString method
- // end of PigLatin class
12Compound Alternatives
- To execute more than one statement conditionally,
you may use to define a compound statement
for either (or both) conditional alternatives - Example
- given two numbers, divide the larger by the
smaller - compute both quotient and remainder
13Compound Alternatives
- if (firstNumber lt secondNumber)
- quotient secondNumber / firstNumber
- remainder secondNumber firstNumber
- // end of ltfirst number is smallergt
- else
- quotient firstNumber / secondNumber
- remainder firstNumber secondNumber
- // end of ltsecond number is smallergt
14Danger Semicolon Ahead
- What would happen in the following code?
- if (p gt q)
- out.println("p gt q")
- How about
- if (x 5)
- out.println("x equals 5")
- else
- out.println("x not equal to 5")
15"Dangling" else Problem
- Code written
- if (condition-1)
- if (condition-2)
- statement-1
- else
- statement-2
- Interpreted as
- if (condition-1)
- if (condition-2)
- statement-1
- else
- statement-2
16(No Transcript)
17(No Transcript)
18Use to solve Dangling else
- if (condition-1)
-
- if (condition-2)
- statement-1
-
- else
- statement-2
19Representing Complex Logic
pseudocode
- enter PIN
- if PIN correct
- enter amount
- if balance gt amount
- dispense
- else
- refuse request
- else
- shred card!
20Nesting if-else Statements
- Example
- if (condition-1)
- statement-1
- else
- if (condition-2)
- statement-2
- else
- statement-3
- Another format
- if (condition-1)
- statement-1
- else if (condition-2)
- statement-2
- else
- statement-3
21(No Transcript)
22Multi-alternative Decisions
- Assign a letter grade for a course according to
the table ? - 5 alternatives
- How do we structure the logic?
- 5 separate decisions?
- A set of cascading decisions?
- How do we implement the logic in Java?
23Compare Java Code
- if (numGrade gt 90)
- letterGrade A
- if (numGrade gt 80 numGrade lt 90)
- letterGrade B
- if (numGrade gt 70 numGrade lt 80)
- letterGrade C
- if (numGrade gt 60 numGrade lt 70)
- letterGrade D
- if (numGrade lt 60)
- letterGrade F
- if (numGrade gt 90)
- letterGrade A
- else if (numGrade gt 80)
- letterGrade B
- else if (numGrade gt 70)
- letterGrade C
- else if (numGrade gt 60)
- letterGrade D
- else
- letterGrade F
24(No Transcript)
25Java Code
- boolean exam_improved (ex1 lt ex2)
(ex2 lt ex3) - boolean hwk_improved (hw1 lt hw2)
(hw2 lt hw3) - if (exam_improved)
- if (hwk_improved)
- out.println(Great overall improvement!)
- else
- out.println(Great exam improvement!)
- else if (hwk_improved)
- out.println(Great homework improvement!)
26calcTaxBlueJ
- public class Payroll
- private double weeklyPay
- public Payroll(double newPay)
- weeklyPay newPay
- // end of GREATLY SIMPLIFIED Payroll
constructor - public double calcTax()
- double taxAmount
- if (weeklyPay gt 2000.00)
- taxAmount 0.35 weeklyPay
- else if (weeklyPay gt 1000.00)
- taxAmount 0.28 weeklyPay
- else if (weeklyPay gt 500.00)
- taxAmount 0.20 weeklyPay
- else if (weeklyPay gt 100.00)
- taxAmount 0.15 weeklyPay
- else
- taxAmount 0.00
- return taxAmount
27Tracing if/else with BlueJ
- Run the Payroll program
- View the Debugger
- Set a breakpoint at the start of the if
structure, and step through the code
28RollTheDiceBlueJ
- public class RollTheDiceApp
- public static String checkDice()
- int die1, die2, dice
- die1 (int)(6Math.random() 1)
- die2 (int)(6Math.random() 1)
- dice die1 die2
- System.out.println("Dice roll " dice)
- if (dice 7 dice 11)
- return "You Win!"
- else if (dice 2)
- return "Snake Eyes!"
- else
- return "Try Again."
- // end of checkDice
- public static void main(String args)
- System.out.println(" " checkDice())
- System.out.println(" " checkDice())
- System.out.println(" " checkDice())
29HW 3 Hint 2
- Create a generic drawBar method which you call 5
times (once for each letter grade) - num on next slide would refer to argument to
method - Send it the vertical bar position for the
particular letter - drawBar(A, numA, 200, g)
- drawBar(B, numB, 250, g)
- drawBar(C, numC, 300, g)
- drawBar(D, numD, 350, g)
- drawBar(F, numF, 400, g)
30HW 3 Hint 3
- private void drawBar(String ltr, int num,
int vertical, Graphics g) - if (num max5(numA,numB,numC,numD,numF))
- g.setColor(Color.GREEN)
- else if (num min5(numA,numB,numC,numD,numF))
- g.setColor(Color.RED)
- else
- g.setColor(Color.BLACK)
-
- g.drawString(ltr, 20, vertical15)
- g.fillRect(40, vertical, 5num, 25)
- // end of drawBar method
- NOTE You would also need to write methods max5
and min5 with 5 int arguments. - Within your max5 you could use nested calls to
Math.max(int,int) - Math.max(a,Math.max(b,Math.max(c,Math.max(d,f))))
31To the Computers...
- Help on HW 3 if you need it
32Java BREAK
33More Multi-Way Decisions
- Menu problems
- User presented with a list of choices
- User asked to enter a letter or number to
represent that choice - The program executes code depending on choice
- Example
- Ask the user for two real numbers and a choice of
whether to add, subtract, multiply, divide the
numbers - Produce the result of the chosen operation
34Algorithm
- get the two numbers
- display a menu of operations
- get the operation
- if the operation is
- compute the result first number second number
- else if the operation is
- compute the result first number - second number
- else if the operation is
- compute the result first number second number
- else if the operation is /
- compute the result first number / second number
- display the result
35Coding Questions
- How should we represent the operation?
- English word?
- Character?
- Integer?
- How should we implement the decision structure?
- Set of one-way ifs
- Cascading (nested) ifs
- Is there another way?
36The Old-Fashioned TV switch
Streamlined Multiway Decisions
37The switch Statement
- Used to accomplish multi-way branching based on
the value of an integer selector variable - Recall that char type is interpreted as integer
- Syntax
- switch ( expression )
- case value1 statements
- case value2 statements
-
- case valuen statements
- default statements
- // end of switch
38Switch Warning
- Java switch statements exhibit drop-through
behavior. - 1. Expression is evaluated.
- 2. If Expression ConstantValuei Control jumps
to the Statement after ConstantValuei. - 3. Control continues within the switch statement
until - a. The end of the switch is reached (i.e. )
- b. A break is executed, terminating the switch
- c. A return is executed, terminating the
function or - d. An exit(0) is executed, terminating the
program.
39Why is break used in switch statements?(MissingBr
eak in BlueJ)
- Consider the code fragment below
- int i 1
- switch (i)
- case 0 System.out.print("zero")
- case 1 System.out.print("one")
- case 2 System.out.print("two")
- case 3 System.out.print("three")
- // end of switch(i)
- System.out.println( )
- Without breaks the output is ???
40Pick the Appropriate Vehicle
- switch (numOfPassengers)
- case 0 ...println(The Harley)
- break
- case 1 ...println(The Dune Buggy)
- break
- default ...println(The Humvee)
- // end of switch(numOfPassengers)
41Comparing switch and if statements
- if equivalent
- switchValue expression
- if (switchValue value1)
- statement1
- else if (switchValue value2)
- statement2
-
- else if (switchValue valuei)
- statementi
- else
- statement(i1)
- switch statement
- switch (expression)
- case value1 statement1 break
- case value2 statement2 break
-
- case valuei statementi break
- default statement(i1)
42Calculator ProgramBlueJ
- Replace
- cascading
- if statements
- with a switch
- See SimpleCalculator program
- validOp true
- if (op '')
- result firstNum secondNum
- else if (op '-')
- result firstNum - secondNum
- else if (op '')
- result firstNum secondNum
- else if (op '/')
- result firstNum / secondNum
- else
- validOp false
43GUI CalculatorBlueJ
- private String doCalculation()
- try
- int a Integer.parseInt(registerA)
- int b Integer.parseInt(registerB)
- int result 0
- switch (operator)
- case '' result a b break
- case '-' result a - b break
- case '' result a b break
- case '/' result a / b break
- default return " E R R O R"
- // end of switch
- return ("" result)
- // end of try
- catch (Exception e)
- System.out.print('\u0007') // beep
- return " E R R O R"
- // end of catch
- // end of doCalculation method
44Symbolic Constants in switch Statements
- final int
- SUNDAY 1, MONDAY 2, TUESDAY 3,
- WEDNESDAY 4, THURSDAY 5, FRIDAY 6,
- SATURDAY 7
- int day String strDay
- ...
- switch (day)
- case SUNDAY strDay Sunday break
- case MONDAY strDay Monday break
- case TUESDAY strDay Tuesday break
- case WEDNESDAY strDay Wednesday break
- case THURSDAY strDay Thursday break
- case FRIDAY strDay Friday break
- case SATURDAY strDay Saturday break
-
- System.out.println(strDay)
45Multiple case Labels in switch Statements
- switch (day)
- case MONDAY
- case WEDNESDAY
- case FRIDAY
- Ssytem.out.println(Math meets at 900
today) - System.out.println(History meets at 1000
today) - break
- case TUESDAY
- case THURSDAY
- System.out.println(CS meets at 915 today)
- System.out.println(Chemistry meets at 200
today) - break
- default
- System.out.println(Enjoy the weekend!)
- // end of switch(day)
46Calculate Days in a Month
- Input month and 4-digit year
- "30 days hath September" and all that
- Need to worry about Leap Years for February
- Years that are evenly divisible by 400, or are
evenly divisible by 4 and not by 100
47Is it a Leap Year?
- if ((year 400 0)
- ((year 4 0) (year 100 ! 0)))
- then it is a leap year
- else
- it is not a leap year
48Days In Month?BlueJ
- import javax.swing.
- public class DaysInMonthApp
- public static void main(String args)
- int month Integer.parseInt(JOptionPane.showI
nputDialog("Month?")) - int year Integer.parseInt(JOptionPane.showIn
putDialog("Year?")) - System.out.println("Days in Month "
daysInMonth(month,year)) - // end of main method
- private static boolean leapYear(int year)
- return (year400 0) (year4 0
year100 ! 0) - // end of leapYear method
- private static int daysInMonth(int mon, int yr)
- switch (mon)
- case 9 case 4 case 6 case 11
- return 30 // note no break needed
- case 2
- if (leapYear(yr))
- return 29
- else
- return 28
49Letter Grade to Grade Points
- double gradePoints(char grade, char plusMinus)
- double gp
- switch (grade)
- case 'A' gp 4.0 break
- case 'B' gp 3.0 break
- case 'C' gp 2.0 break
- case 'D' gp 1.0 break
- case 'F' gp 0.0 break
- default gp -1.0
- // end of "grade" switch
- switch (plusMinus)
- case '' gp 0.3 break
- case '-' gp - 0.3 break
- // end of "plusMinus" switch
- return gp
- // end of gradePoints method
50Ordinal SuffixBlueJ
- Write an application to read an integer n between
0 and 100, and write n followed by the
appropriate ordinal suffix - (20th, 21st, 23rd, or 22nd).
- How do we start? What are the rules?
- Implementation nested if? switch?
- See OrdinalSuffix
51To the Computers...
- Try GUI "Calculator"
- Some features have not been covered as yet
- button clicking events, etc.
- Drag from course folder to My Documents
52Java BREAK