Chapter 3 Program Statements Metcalfe County High School

  • Slides: 53
Download presentation
Chapter 3: Program Statements Metcalfe County High School Computer Programming II Justin Smith -

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

Program Development Ø The creation of software involves four basic activities: • establishing the

Program Development Ø The creation of software involves four basic activities: • establishing the requirements • creating a design • implementing the code • testing 2

Requirements Ø Software requirements specify the tasks a program must accomplish (what to do,

Requirements Ø 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 3

Design Ø A software design specifies how a program will accomplish its requirements Ø

Design Ø 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 4

Implementation Ø Implementation is the process of translating a design into source code Ø

Implementation Ø 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) 5

Testing Ø A program should be executed multiple times with various input in an

Testing Ø 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 6

Flow of Control Ø Unless specified otherwise, the order of statement execution through a

Flow 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 7

Conditional Statements Ø A conditional statement lets us choose which statement will be executed

Conditional 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 8

The if Statement Ø The if statement has the following syntax: if is a

The if Statement Ø The if statement has the following syntax: if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. 9

Logic of an if statement condition evaluated true false statement 10

Logic of an if statement condition evaluated true false statement 10

Equality & Relational Operators Ø A condition often uses one of Java's equality operators

Equality & 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 (=) 11

The if Statement Ø An example of an if statement: if (sum > MAX)

The 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 sum is 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. 12

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

Assignment Ø 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 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” 13

The if-else Statement Ø An else clause can be added to an if statement

The if-else Statement Ø An else clause can be added to an if statement to make an if-else statement if ( condition ) statement 1; else statement 2; Ø If the condition is true, statement 1 is executed; if the condition is false, statement 2 is executed Ø One or the other will be executed, but not both 14

Logic of an if-else statement condition evaluated true false statement 1 statement 2 15

Logic of an if-else statement condition evaluated true false statement 1 statement 2 15

If-Else Program Snapshot Ø Input the code from the handout within the program called

If-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. 16

Assignment Ø Code the Wages. java program found on page 130 Ø _____________________ Ø

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. 17

Block Statements Ø Several statements can be grouped together into a block statement Ø

Block 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. ** 18

Nested if Statements Ø The statement executed as a result of an if statement

Nested 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 (Min. Of. Three. java) to see how a nested If statement can be used to determine the minimum value. ********************************** Ø Using the Min. Of. Three program revise the code to figure out the highest value for the numbers that have been entered. 19

Logical Operators Ø Logical operators: ! && || NOT AND OR 20

Logical Operators Ø Logical operators: ! && || NOT AND OR 20

Logical NOT Ø If some boolean condition a is true, then !a is false;

Logical 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 true 21

Logical AND and Logical OR Ø The logical AND expression a && b both

Logical 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 both are true, and false otherwise 22

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

Truth Tables Ø A truth table shows the possible true/false combinations of the terms a b a && b a || b true true false true false 23

Logical Operators Ø Example using logical operators if (total < MAX+5 && !found) System.

Logical Operators Ø Example using logical operators if (total < MAX+5 && !found) System. out. println ("Processing…"); 24

Challenge Program Ø Ø Ø Ø Activities at Lake Lazy. Days As activity directory

Challenge Program Ø Ø Ø Ø Activities at Lake Lazy. Days As activity directory at Lake Lazy. Days 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. 25

Challenge Program Ø Using the Dice program and the initial code enhance the program

Challenge 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. 26

Comparing Characters Ø We can use the relational operators on character data Ø The

Comparing 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"); 27

Comparing Strings Ø We cannot use the relational operators to compare strings(==, !=, <,

Comparing 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 compare. To is used to determine if one string comes before another (based on the Unicode character set) Ø Look at pages 138 and 139 for examples. 28

Rock, Paper and Scissors Ø Complete the Rock, Paper and Scissors program handout that

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

Challenge Program Ø Complete the Computing A Raise handout program Ø Part of the

Challenge 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. 30

More Operators Ø To round out our knowledge of Java operators, let's examine a

More 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 31

Increment and Decrement Ø The increment and decrement operators are arithmetic and operate on

Increment 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; 32

Repetition Statements Ø Repetition statements allow us to execute a statement multiple times Ø

Repetition 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 33

The while Statement Ø The while statement has the following syntax: while is a

The while Statement Ø The while statement has the following syntax: while is a reserved word while ( condition ) statement; If the condition is true, the statement is executed. Then the condition is evaluated again. **The While statement is executed repeatedly until the condition becomes false. ** 34

Logic of a while Loop condition evaluated true false statement 35

Logic of a while Loop condition evaluated true false statement 35

The while Statement Ø Note that if the condition of a while statement is

The 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) • Win. Percentage. java(page 147) 36

A Guessing Game Ø Using the skeleton of the guess. java program complete the

A Guessing Game Ø Using the skeleton of the guess. java program complete the requested modifications as found on the handout. 37

Infinite Loops Ø The body of a while loop eventually must make the condition

Infinite 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. 38

The String. Tokenizer Class Ø The elements that comprise a string are referred to

The String. Tokenizer 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 String. Tokenizer class, which is defined in the java. util package, is used to separate a string into tokens 39

The String. Tokenizer Class Ø The String. Tokenizer class has value but for the

The String. Tokenizer Class Ø The String. Tokenizer class has value but for the time being we will look at an example within the text. Ø Code the program on page 155 (Count. Words. java) to see how the String. Tokenizer is used. 40

The for Statement Ø The for statement has the following syntax and 3 main

The 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++) 41

Logic of a for loop initialization condition evaluated true false statement increment 42

Logic of a for loop initialization condition evaluated true false statement increment 42

The for Statement Ø Like a while loop, the condition of a for statement

The 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. 43

The for Statement Example of a for statement. What does this for statement tell

The 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 44

Assignment Ø For Loop Practice Ø Code the Counter 2. java program on page

Assignment Ø For Loop Practice Ø Code the Counter 2. 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 5 th name is entered all names will be printed. 45

Choosing a Loop Structure Ø When you can’t determine how many times you want

Choosing 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 46

Program Development Ø Initial Program requirements: • accept a series of test scores •

Program 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 Exam. Grades. java to see how various control structures and code can be combined into one program. 47

Programming Projects Ø Break into groups of 2 Ø Choose two of the following

Programming 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 48

More Drawing Techniques Ø Conditionals and loops can greatly enhance our ability to control

More 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) Ø Bar. Heights. java (page 173) 49

Enhance the Applets Ø Bullseye. java • Change the color sequence of the rings

Enhance 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. 50

Enhance The Applets Ø Boxes. java • • • 125 boxes need to be

Enhance 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) 51

Applet Projects Ø Complete the following applets(100 points each). Refer back to previous examples

Applet 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 52

Applet Enhanced Ø Using the Staircase Applet Add the following to help reinforce your

Applet 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. 53