Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith -...

53
Chapter 3: Program Chapter 3: Program Statements Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor

Transcript of Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith -...

Page 1: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

Chapter 3: Program Statements Chapter 3: Program Statements

Metcalfe County High School

Computer Programming II

Justin Smith - Instructor

Page 2: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

2

Program DevelopmentProgram Development

The creation of software involves four basic activities:

• establishing the requirements

• creating a design

• implementing the code

• testing

Page 3: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

3

RequirementsRequirements

Software requirements specify the tasks a program must accomplish (what to do, not how to do it)

Careful attention to the requirements can save significant time and expense in the overall project

Page 4: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

4

DesignDesign

A software design specifies how a program will accomplish its requirements

In object-oriented development, the design establishes the classes, objects, methods, and data that are required

Page 5: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

5

ImplementationImplementation

Implementation is the process of translating a design into source code

Most novice programmers think that writing code is the heart of software development, but actually it should be the least creative step

Almost all important decisions are made during requirements and design stages

Implementation should focus on coding details, including style guidelines and documentation(Comments and White space)

Page 6: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

6

TestingTesting

A program should be executed multiple times with various input in an attempt to find errors

Debugging is the process of discovering the causes of problems and fixing them

Page 7: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

7

Flow of ControlFlow of Control

Unless specified otherwise, the order of statement execution through a method is top to bottom: one statement after the other in sequence

Some programming statements modify that order, allowing us to:

• decide whether or not to execute a particular statement, or• perform a statement over and over, repetitively

Page 8: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

8

Conditional StatementsConditional Statements

A conditional statement lets us choose which statement will be executed next

Conditional statements give us the power to make basic decisions

Some conditional statements in Java are • the if statement• the if-else statement

Page 9: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

9

The if StatementThe if Statement

The if statement has the following syntax:

if ( condition ) statement;

if is a Javareserved word

The condition must be a boolean expression.It must evaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Page 10: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

10

Logic of an if statementLogic of an if statement

conditionevaluated

false

statement

true

Page 11: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

11

Equality & Relational OperatorsEquality & Relational Operators

A condition often uses one of Java's equality operators or relational operators, which all return boolean(true or false) results:

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

Note the difference between the equality operator (==) and the assignment operator (=)

Page 12: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

12

The if StatementThe if Statement

An example of an if statement:

if (sum > MAX) delta = sum - MAX;System.out.println ("The sum is " + sum);

First, the condition is evaluated. The value of sumis either greater than the value of MAX, or it is not.

If the condition is true, the assignment statement is executed.If it is not, the assignment statement is skipped.

Either way, the call to println is executed next.

Page 13: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

13

AssignmentAssignment

Code the Age.java program on page 126 to demonstrate an If statement.

_____________________________________________ Design a program that asks the user to enter the

following information.• Cash on Hand• Computed Balance(determined by a machine)

If the Cash on Hand and the Computed Balance are not the same an error message should appear that says “Recalculate Cash on Hand” if the two values match a message should appear that says “Well Done”

Page 14: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

14

The if-else StatementThe if-else Statement

An else clause can be added to an if statement to make an if-else statement

if ( condition ) statement1;else statement2;

If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

One or the other will be executed, but not both

Page 15: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

15

Logic of an if-else statementLogic of an if-else statement

conditionevaluated

statement1

true false

statement2

Page 16: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

16

If-Else Program SnapshotIf-Else Program Snapshot

Input the code from the handout within the program called Grades.java.

Design the written response to explain to your boss (Jane Monroe) what the program does and how it operates.

Page 17: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

17

Assignment Assignment

Code the Wages.java program found on page 130 _________________________________________ Using the Wages.java program make the following

modifications.• Ask the user for the total number of hours worked • Ask the user for the amount($) they make per hour• Calculate and display the gross earnings (amount * total

hours worked)• Calculate the Net Pay gross pay - (gross pay * .3) • New variables may have to be created• Each value such as gross and net pay should be displayed

as currency.

Page 18: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

18

Block StatementsBlock Statements

Several statements can be grouped together into a block statement

A block is delimited by braces : { … }

A block statement can be used wherever a statement extends beyond one line.

For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements

**Code the program found on page 132 called Guessing.java to see how a block statement works. **

Page 19: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

19

Nested if StatementsNested if Statements

The statement executed as a result of an if statement or else clause could be another if statement

These are called nested if statements

An else clause is matched to the last unmatched if

Code the program found on page 134 (MinOfThree.java) to see how a nested If statement can be used to determine the minimum value.

**********************************************************************************

Using the MinOfThree program revise the code to figure out the highest value for the numbers that have been entered.

Page 20: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

20

Logical OperatorsLogical Operators

Logical operators:

! NOT

&& AND

|| OR

Page 21: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

21

Logical NOTLogical NOT

If some boolean condition a is true, then !a is false; if a is false, then !a is true

! Operator takes the initial value and changes it to the opposite.

a !a

true false

false true

Page 22: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

22

Logical AND and Logical ORLogical AND and Logical OR

The logical AND expression

a && b

both must be true in order to get an answer of true.

The logical OR expression

a || b

is true if a or b or both are true, and false otherwise

Page 23: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

23

Truth TablesTruth Tables

A truth table shows the possible true/false combinations of the terms

a b a && b a || b

true true true true

true false false true

false true false true

false false false false

Page 24: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

24

Logical OperatorsLogical Operators

Example using logical operators

if (total < MAX+5 && !found) System.out.println ("Processing…");

Page 25: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

25

Challenge Program Challenge Program

Activities at Lake LazyDays As activity directory at Lake LazyDays Resort, it is

your job to suggest appropriate activities to guests based on the weather:

Temp >= 80: swimming Temp >=60 and < 80: tennis Temp >=40 and <60: golf Temp < 40: skiing Write a program that prompts the user for a

temperature, then prints out the activity appropriate for that temperature. Use an if-else statement to complete your program.

Page 26: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

26

Challenge ProgramChallenge Program

Using the Dice program and the initial code enhance the program to make the following modifications.

Design your very own dice game with a specific set of rules. Your program must first introduce the program to the user and explain the purpose, rules and any other information that the user might need.

The program should then roll the dice and display the results

Using Your knowledge of If, If-Else, Logical operators or any other conditional statement have your program evaluate the roll and display a message to the user.

It is your game but ensure that the rules and directions match up to the code that is used.

Page 27: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

27

Comparing CharactersComparing Characters

We can use the relational operators on character data

The results are based on the Unicode character set(PAGE 604 in your book)

The following condition is true because the character + comes before the character J in the Unicode character set:

if ('+' < 'J') System.out.println ("+ is less than J");

Page 28: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

28

Comparing StringsComparing Strings

We cannot use the relational operators to compare strings(==, !=, <,>, etc)

The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order

A method called compareTo is used to determine if one string comes before another (based on the Unicode character set)

Look at pages 138 and 139 for examples.

Page 29: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

29

Rock, Paper and ScissorsRock, Paper and Scissors

Complete the Rock,Paper and Scissors program handout that will be provided to gain more insight to comparing characters.

Page 30: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

30

Challenge ProgramChallenge Program

Complete the Computing A Raise handout program Part of the code is given but an If-Else statement

must be included to finish the program. Make sure to pay special attention to the note on the

string comparison operator. Use page 138 for help with the .equals operator.

Page 31: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

31

More OperatorsMore Operators

To round out our knowledge of Java operators, let's examine a few more

In particular, we will examine

• the increment and decrement operators

• the assignment operators

Page 32: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

32

Increment and DecrementIncrement and Decrement

The increment and decrement operators are arithmetic and operate on one operand

The increment operator (++) adds one to its operand

The decrement operator (--) subtracts one from its operand

The statement

count++;

is functionally equivalent to

count = count + 1;

Page 33: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

33

Repetition StatementsRepetition Statements

Repetition statements allow us to execute a statement multiple times

Often they are referred to as loops

Like conditional statements, they are controlled by Boolean expressions

The text covers two kinds of repetition statements:

• the while loop• the for loop

The programmer should choose the right kind of loop for the situation

Page 34: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

34

The while StatementThe while Statement

The while statement has the following syntax:

while ( condition ) statement;

while is areserved word

If the condition is true, the statement is executed.Then the condition is evaluated again.

**The While statement is executed repeatedly untilthe condition becomes false.**

Page 35: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

35

Logic of a while LoopLogic of a while Loop

statement

true

conditionevaluated

false

Page 36: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

36

The while StatementThe while Statement

Note that if the condition of a while statement is false initially, the statement is never executed

Therefore, the body of a while loop will execute zero or more times

****************************************************************

Assignment

Code the following

• Counter.java(page 143)

• Average.java(page 144)

• WinPercentage.java(page147)

Page 37: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

37

A Guessing GameA Guessing Game

Using the skeleton of the guess.java program complete the requested modifications as found on the handout.

Page 38: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

38

Infinite LoopsInfinite Loops

The body of a while loop eventually must make the condition false

If not, it is an infinite loop, which will execute until the user interrupts the program

This is a common error

You should always double check to ensure that your loops will terminate normally

Ctrl-C stops an infinite loop

Code the program on page 148 to see what happens when an infinite loop is coded into a program.

Page 39: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

39

The StringTokenizer ClassThe StringTokenizer Class

The elements that comprise a string are referred to as tokens

The process of extracting these elements is called tokenizing

Characters that separate one token from another are called delimiters

The StringTokenizer class, which is defined in the java.util package, is used to separate a string into tokens

Page 40: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

40

The StringTokenizer ClassThe StringTokenizer Class

The StringTokenizer class has value but for the time being we will look at an example within the text.

Code the program on page 155 (CountWords.java) to see how the StringTokenizer is used.

Page 41: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

41

The for StatementThe for Statement

The for statement has the following syntax and 3 main parts:

for ( initialization ; condition ; increment ) statement;

For (int count = 1; count<=Limit; count++)

Page 42: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

42

Logic of a for loopLogic of a for loop

statement

true

conditionevaluated

false

increment

initialization

Page 43: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

43

The for StatementThe for Statement

Like a while loop, the condition of a for statement is tested prior to executing the loop body

Therefore, the body of a for loop will execute zero or more times

It is well suited for executing a loop a specific number of times that can be determined in advance

If you do not know how many times code will execute a while loop should be used.

Page 44: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

44

The for StatementThe for Statement

Example of a for statement.

What does this for statement tell you????

For (int row = 1; row <=MAX_ROWS;row++)

Both semi-colons are always required in the for loop header

Page 45: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

45

AssignmentAssignment

For Loop Practice

Code the Counter2.java program on page 157 to see how a For loop is executed.

Code the Stars.java program on page 161 to see a nested for loop.

Design a program that will accept 5 names to be entered for a class and then after the 5th name is entered all names will be printed.

Page 46: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

46

Choosing a Loop StructureChoosing a Loop Structure

When you can’t determine how many times you want to execute the loop body, use a while statement

If you can determine how many times you want to execute the loop body, use a for statement

Page 47: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

47

Program DevelopmentProgram Development

Initial Program requirements:

• accept a series of test scores

• compute the average test score

• determine the highest and lowest test scores

• display the average, highest, and lowest test scores

Code the program on page 164 ExamGrades.java to see how various control structures and code can be combined into one program.

Page 48: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

48

Programming ProjectsProgramming Projects

Break into groups of 2 Choose two of the following to complete for a 100 per

program grade pages 183 - 184 Programming Projects

• 3.3• 3.4• 3.5• 3.6• 3.7

Choose one of the following challenge programs(150 points) pages 184 - 185• 3.11• 3.13• 3.16

Page 49: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

49

More Drawing TechniquesMore Drawing Techniques

Conditionals and loops can greatly enhance our ability to control graphics

Applets that use control structures.

Code the following.

Bullseye.java (page 169)

Boxes.java (page 171)

BarHeights.java (page 173)

Page 50: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

50

Enhance the AppletsEnhance the Applets

Bullseye.java • Change the color sequence of the rings to Black, Yellow,

Blue.• The bullseye needs to have 9 rings• The bullseye needs to be white• Change the background color.• Use pages 100-107 for help with colors and other applet

features.

Page 51: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

51

Enhance The AppletsEnhance The Applets

Boxes.java• 125 boxes need to be used in the applet.• If the width is <= Thickness a blue oval should be drawn• If height <= Thickness a yellow oval should be drawn• If width = height a white oval should be drawn• Otherwise if none of the above are met draw an orange

rectangle.• Include a title to your program(Page 101 for text help)

Page 52: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

52

Applet ProjectsApplet Projects

Complete the following applets(100 points each). Refer back to previous examples for code help, conditional statements will be used within both programs in order for them to work correctly. 3.17 can be created without a conditional statement but several lines of code will be required. • 3.17• 3.18

Page 53: Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith - Instructor.

53

Applet EnhancedApplet Enhanced

Using the Staircase Applet Add the following to help reinforce your applet skills.• Add a window between your staircase and the upper left

hand side of the applet.• One should be able to see green grass and the blue sky

through the window. The green grass can be a green rectangle.

• Add a picture frame between your staircase and the lower right hand bottom of the applet. The color of the frame is up to you but it should contain a yellow smiling face with 2 eyes and a mouth

• Using the side of your applet below the staircase and to the right add a door that will take a person in under the stairs. The door should be brown with a black door handle. The door should have a sign that reads “Enter At Your Own Risk”. The color of the text and sign is up to the designer.