1 / 53

Chapter 3: Program Statements

Learn the four basic activities of software development - establishing requirements, creating a design, implementing the code, and testing. Understand the importance of careful attention to requirements and design, and the role of implementation and testing in the development process.

linneag
Download Presentation

Chapter 3: Program Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. Design • A software design specifies howa program will accomplish its requirements • In object-oriented development, the design establishes the classes, objects, methods, and data that are required

  5. 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)

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

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

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

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

  10. condition evaluated true false statement Logic of an if statement

  11. Equality & Relational Operators • A condition often uses one of Java's equality operatorsor 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 (=)

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

  13. 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 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”

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

  15. condition evaluated true false statement1 statement2 Logic of an if-else statement

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

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

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

  19. 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 (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.

  20. Logical Operators • Logical operators: !NOT && AND || OR

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

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

  23. Truth Tables • A truth table shows the possible true/false combinations of the terms

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

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

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

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

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

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

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

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

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

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

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

  35. condition evaluated true false statement Logic of a while Loop

  36. 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) • WinPercentage.java(page147)

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

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

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

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

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

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

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

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

  45. Assignment • 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.

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

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

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

  49. 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) • BarHeights.java (page 173)

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

More Related