Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Similar documents
Chapter 3: Program Statements

Conditionals and Loops

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Chapter 4: Conditionals and Loops

Program Elements -- Introduction

Java Flow of Control

Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops

CS1004: Intro to CS in Java, Spring 2005

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Algorithms and Conditionals

CMPT 125: Lecture 4 Conditionals and Loops

Chapter 3. Selections

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

More Programming Constructs -- Introduction

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Conditional Programming

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

BRANCHING if-else statements

Program Planning, Data Comparisons, Strings

Full file at

COMP Primitive and Class Types. Yi Hong May 14, 2015

Information Science 1

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

STUDENT LESSON A12 Iterations

Conditional Statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Information Science 1

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 5: Enhancing Classes

Fundamentals of Programming Session 7

Chapter 3: Program Statements

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Java I/O and Control Structures

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Loops / Repetition Statements

Java I/O and Control Structures Algorithms in everyday life

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Looping. Arizona State University 1

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Operators. Java operators are classified into three categories:

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Chapter. Let's explore some other fundamental programming concepts

5. Control Statements

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

COMP 202 Java in one week

ECE 122 Engineering Problem Solving with Java

Flow of Control. Chapter 3. Chapter 3 1

CT 229 Java Syntax Continued

Chapter 3: Operators, Expressions and Type Conversion

1007 Imperative Programming Part II

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Basics of Java Programming

Repetition and Loop Statements Chapter 5

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to Java & Fundamental Data Types

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Repetition Structures

CMPT 125: Lecture 3 Data and Expressions

Topics. Chapter 5. Equality Operators

CS110D: PROGRAMMING LANGUAGE I

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

CS111: PROGRAMMING LANGUAGE II

Chapter 4: Control Structures I (Selection)

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Control Statements: Part 1

Flow Control. So Far: Writing simple statements that get executed one after another.

Chapter 2: Data and Expressions

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M


Operators & Expressions

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

COMP 202. Java in one week

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Control Structures: if and while A C S L E C T U R E 4

Transcription:

Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition Program Development The creation of software involves four basic activities: establishing the requirements creating a design implementing the code by John Lewis, William Loftus, and Cara Cocking testing the implementation Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2006 by John Lewis, William Loftus, and Cara Cocking. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes. *AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product. The development process is much more involved than this, but these are the four basic development activities 3 Program Statements Requirements Now we will examine some other program statements Chapter 3 focuses on: program development stages the flow of control through a method decision-making statements expressions for making complex decisions repetition statements drawing with conditionals and loops Software requirements specify the tasks a program must accomplish (what to do, not how to do it) They often include a description of the user interface An initial set of requirements often are provided, but usually must be critiqued, modified, and expanded Often it is difficult to establish detailed, unambiguous, complete requirements Careful attention to the requirements can save significant time and expense in the overall project 2 4 1

Design Testing A software design specifies how a program will accomplish its requirements A program should be executed multiple times with various input in an attempt to find errors A design includes one or more algorithms to accomplish its goal An algorithm is a step-by-step process for solving a problem An algorithm may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax Debugging is the process of discovering the causes of problems and fixing them Programmers often think erroneously that there is "only one more bug" to fix Tests should consider design details as well as overall requirements In object-oriented development, the design establishes the classes, objects, methods, and data that are required 5 7 Implementation Flow of Control 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 Unless specified otherwise, the order of statement execution through a method is linear: 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 These decisions are based on a boolean expression (also called a condition) that evaluates to true or false The order of statement execution is called the flow of control 6 8 2

Conditional Statements A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions Some conditional statements in Java are the if statement the if-else statement 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. See Age.java (page 130) 9 11 The if Statement Logic of an 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. condition evaluated if ( condition ) statement; true statement false If the condition is true, the statement is executed. If it is false, the statement is skipped. 10 12 3

Boolean Expressions Logic of an if-else statement A condition often uses one of Java's equality operators or relational operators, which all return boolean 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 (=) condition evaluated true statement1 false statement2 13 15 The if-else Statement Block Statements An else clause can be added to an if statement to make an if-else statement Several statements can be grouped together into a block statement if ( condition ) statement1; else statement2; A block is delimited by braces : { } A block statement can be used wherever a statement is called for by the Java syntax 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 See Wages.java (page 134) For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements See Guessing.java (page 136) 14 16 4

Nested if Statements Logical NOT The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true See MinOfThree.java (page 138) An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs Logical expressions can be shown using truth tables a!a true false false true 17 19 Logical Operators Logical AND and Logical OR Boolean expressions can use the following logical operators:! Logical NOT && Logical AND Logical OR They all take boolean operands and produce boolean results The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b Logical NOT is a unary operator (it operates on one operand) is true if a or b or both are true, and false otherwise Logical AND and logical OR are binary operators (each operates on two operands) 18 20 5

Truth Tables Short Circuited Operators A truth table shows the possible true/false combinations of the terms The processing of logical AND and logical OR is short-circuited Since && and each have two operands, there are four possible combinations of conditions a and b If the left operand is sufficient to determine the result, the right operand is not evaluated a b a && b a b true true true true if (count!= 0 && total/count > MAX) System.out.println ("Testing "); true false false true false true false true This type of processing must be used carefully false false false false 21 23 Logical Operators Truth Tables Conditions can use logical operators to form complex expressions Specific expressions can be evaluated using truth tables if (total < MAX+5 &&!found) System.out.println ("Processing "); total < MAX found!found total < MAX &&!found false false true false Logical operators have precedence relationships among themselves and with other operators all logical operators have lower precedence than the relational or arithmetic operators logical NOT has higher precedence than logical AND and logical OR false true false false true false true true true true false false 22 24 6

Comparing Characters Lexicographic Ordering We can use the relational operators on character data The results are based on the Unicode character set 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"); The uppercase alphabet (A-Z) followed by the lowercase alphabet (a-z) appear in alphabetical order in the Unicode character set 25 Because comparing characters and strings is based on a character set, it is called a lexicographic ordering This is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase" 27 Comparing Strings Remember that a character string in Java is an object We cannot use the relational operators to compare strings The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The String class also contains a method called compareto to determine if one string comes before another (based on the Unicode character set) Comparing Float Values We also have to be careful when comparing two floating point values (float or double) for equality You should rarely use the equality operator (==) when comparing two floats In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal Therefore, to determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < 0.00001) System.out.println ("Essentially equal."); 26 28 7

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 Assignment Operators Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; 29 31 Increment and Decrement Assignment Operators The increment and decrement operators are arithmetic and operate on one operand There are many assignment operators, including the following: The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y count = count + 1; 30 32 8

Assignment Operators Repetition Statements The right hand side of an assignment operator can be a complex expression Repetition statements allow us to execute a statement multiple times The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore is equivalent to result /= (total-min) % num; 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 result = result / ((total-min) % num); The programmer should choose the right kind of loop for the situation 33 35 Assignment Operators The while Statement The behavior of some assignment operators depends on the types of the operands The while statement has the following syntax: If the operands to the += operator are strings, the assignment operator performs string concatenation The behavior of an assignment operator (+=) is always consistent with the behavior of the "regular" operator (+) while is a reserved word while ( condition ) statement; If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repeatedly until the condition becomes false. 34 36 9

Logic of a while Loop Infinite Loops The body of a while loop eventually must make the condition false condition evaluated true statement false If not, it is an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check to ensure that your loops will terminate normally See Forever.java (page 152) 37 39 The while Statement Nested Loops Note that if the condition of a while statement is false initially, the statement is never executed Similar to nested if statements, loops can be nested as well Therefore, the body of a while loop will execute zero or more times See Counter.java (page 147) See Average.java (page 148) A sentinel value indicates the end of the input The variable sum maintains a running sum That is, the body of a loop can contain another loop Each time through the outer loop, the inner loop goes through its full set of iterations See PalindromeTester.java (page 155) See WinPercentage.java (page 151) A loop is used to validate the input, making the program more robust 38 40 10

Iterators An iterator is an object that has methods that allow you to process a collection of items one at a time The hasnext and next methods are used to loop through the collection while (mycollection.hasnext()) { System.out.println(myCollection.next()); } Several classes in the Java class library define iterator objects, including Scanner The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } See URLDissector.java (page 158) 41 43 The for Statement Logic of a for loop The for statement has the following syntax: Reserved word The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration The condition-statement-increment cycle is executed repeatedly initialization condition evaluated true statement increment false 42 44 11

The for Statement Iterators and for Loops 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 See Counter2.java (page 161) See Multiples.java (page 163) A variation of the for loop, called the foreach loop, allows us to process collections just like iterators, but without the complicated syntax If booklist is an iterator object that manages Book objects, we can do the following: for (Book mybook : booklist) { System.out.println(myBook); } See Stars.java (page 165) See IceCreamShop.java (page 167) 45 47 The for Statement Choosing a Loop Structure Each expression in the header of a for loop is optional When you can t determine how many times you want to execute the loop body, use a while statement If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed If you can determine how many times you want to execute the loop body, use a for statement Both semi-colons are always required in the for loop header 46 48 12

Program Development Program Development We now have several additional statements and operators at our disposal Following proper development steps is important Suppose you were given some initial requirements: accept a series of test scores Design determine a possible general solution Input strategy? (Sentinel value?) Calculations needed? An initial algorithm might be expressed in pseudocode compute the average test score determine the highest and lowest test scores display the average, highest, and lowest test scores Multiple versions of the solution might be needed to refine it Alternatives to the solution should be carefully considered 49 51 Program Development Program Development Requirements Analysis clarify and flesh out specific requirements How much data will there be? How should data be accepted? Is there a specific output format required? After conferring with the client, we determine: the program must process an arbitrary number of test scores the program should accept input interactively the average should be presented to two decimal places The process of requirements analysis may take a long time 50 Implementation translate the design into source code Make sure to follow coding and style guidelines Implementation should be integrated with compiling and testing your solution This process mirrors a more complex development model we'll eventually need to develop more complex software The result is a final implementation See ExamGrades.java (page 170) 52 13

Program Development Testing attempt to find errors that may exist in your programmed solution Compare your code to the design and resolve any discrepancies Determine test cases that will stress the limits and boundaries of your solution Summary Chapter 3 has focused on: program development stages the flow of control through a method decision-making statements expressions for making complex decisions repetition statements drawing with conditionals and loops Carefully retest after finding and fixing an error 53 55 More Drawing Techniques Conditionals and loops can greatly enhance our ability to control graphics See Bullseye.java (page 173) See Boxes.java (page 175) See BarHeights.java (page 177) 54 14