SlideShare a Scribd company logo
1
Program Statements
 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
2
Program Development
 The creation of software involves four basic
activities:
• establishing the requirements
• creating a design
• implementing the code
• testing the implementation
 The development process is much more involved
than this, but these are the four basic development
activities
3
Requirements
 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
4
Design
 A software design specifies how a program will
accomplish its requirements
 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
 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
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
 Programmers often think erroneously that there is
"only one more bug" to fix
 Tests should consider design details as well as
overall requirements
7
Flow of Control
 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
8
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
9
The if Statement
 The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved 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.
10
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 126)
11
Logic of an if statement
condition
evaluated
false
statement
true
12
Boolean Expressions
 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 (=)
13
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;
 See Wages.java (page 130)
 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
14
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
15
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
is called for by the Java syntax
 For example, in an if-else statement, the if
portion, or the else portion, or both, could be block
statements
 See Guessing.java (page 132)
16
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
 See MinOfThree.java (page 134)
 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
17
Logical Operators
 Boolean expressions can use the following logical
operators:
! Logical NOT
&& Logical AND
|| Logical OR
 They all take boolean operands and produce boolean
results
 Logical NOT is a unary operator (it operates on one
operand)
 Logical AND and logical OR are binary operators
(each operates on two operands)
18
Logical NOT
 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
 Logical expressions can be shown using truth
tables
a !a
true false
false true
19
Logical AND and Logical OR
 The logical AND expression
a && b
is true if both a and b are true, and false otherwise
 The logical OR expression
a || b
is true if a or b or both are true, and false otherwise
20
Truth Tables
 A truth table shows the possible true/false
combinations of the terms
 Since && and || each have two operands, there are
four possible combinations of conditions a and b
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
21
Logical Operators
 Conditions can use logical operators to form
complex expressions
if (total < MAX+5 && !found)
System.out.println ("Processing…");
 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
22
Short Circuited Operators
 The processing of logical AND and logical OR is
“short-circuited”
 If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println ("Testing…");
 This type of processing must be used carefully
23
Truth Tables
 Specific expressions can be evaluated using truth
tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
24
Comparing Characters
 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
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)
26
Lexicographic Ordering
 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 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.");
28
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
29
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;
30
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;
31
Assignment Operators
 There are many assignment operators, including the
following:
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
32
Assignment Operators
 The right hand side of an assignment operator can be
a complex expression
 The entire right-hand expression is evaluated first,
then the result is combined with the original variable
 Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
33
Assignment Operators
 The behavior of some assignment operators depends
on the types of the operands
 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 (+)
34
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
35
The while Statement
 The while statement has the following syntax:
while ( condition )
statement;
while is a
reserved word
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.
36
Logic of a while Loop
statement
true
condition
evaluated
false
37
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
 See Counter.java (page 143)
 See Average.java (page 144)
• A sentinel value indicates the end of the input
• The variable sum maintains a running sum
 See WinPercentage.java (page 147)
• A loop is used to validate the input, making the program
more robust
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 logical error
 You should always double check to ensure that your
loops will terminate normally
 See Forever.java (page 148)
39
Nested Loops
 Similar to nested if statements, loops can be nested
as well
 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 151)
40
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
41
The StringTokenizer Class
 The default delimiters are space, tab, carriage return,
and the new line characters
 The nextToken method returns the next token
(substring) from the string
 The hasMoreTokens returns a boolean indicating if
there are more tokens to process
 See CountWords.java (page 155)
42
The for Statement
 The for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
Reserved
word
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is executed at the end of each iteration
The condition-statement-increment cycle is executed repeatedly
43
The for Statement
 A for loop is functionally equivalent to the following
while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
44
Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
45
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
 See Counter2.java (page 157)
 See Multiples.java (page 159)
 See Stars.java (page 161)
46
The for Statement
 Each expression in the header of a for loop is
optional
• 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
 Both semi-colons are always required in the for loop
header
47
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
48
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
• compute the average test score
• determine the highest and lowest test scores
• display the average, highest, and lowest test scores
49
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
Program Development
 Design – determine a possible general solution
• Input strategy? (Sentinel value?)
• Calculations needed?
 An initial algorithm might be expressed in
pseudocode
 Multiple versions of the solution might be needed to
refine it
 Alternatives to the solution should be carefully
considered
51
Program Development
 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 164)
52
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
 Carefully retest after finding and fixing an error
53
More Drawing Techniques
 Conditionals and loops can greatly enhance our
ability to control graphics
 See Bullseye.java (page 169)
 See Boxes.java (page 171)
 See BarHeights.java (page 173)
54
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

More Related Content

Similar to Lewis_Cocking_AP_Decision_Making_For_Coding (20)

PDF
Week03
hccit
 
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
PDF
Java input Scanner
Huda Alameen
 
PPTX
Pi j1.3 operators
mcollison
 
PPTX
Chapter 4.1
sotlsoc
 
PPTX
Java chapter 3
Abdii Rashid
 
PPT
Java Programmin: Selections
Karwan Mustafa Kareem
 
PDF
data types.pdf
HarshithaGowda914171
 
PPTX
02 Java Language And OOP PART II
Hari Christian
 
PPTX
Java developer trainee implementation and import
iamluqman0403
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPTX
Conditional Statement
OXUS 20
 
PPT
Chap04
Terry Yoast
 
PPTX
Programming fundamentals through javascript
Codewizacademy
 
PPTX
UNIT 2 programming in java_operators.pptx
jijinamt
 
PDF
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
PPTX
Std 12 Computer Chapter 7 Java Basics (Part 2)
Nuzhat Memon
 
PPTX
Introduction to Java
Ashita Agrawal
 
PDF
java basics - keywords, statements data types and arrays
mellosuji
 
Week03
hccit
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
Java input Scanner
Huda Alameen
 
Pi j1.3 operators
mcollison
 
Chapter 4.1
sotlsoc
 
Java chapter 3
Abdii Rashid
 
Java Programmin: Selections
Karwan Mustafa Kareem
 
data types.pdf
HarshithaGowda914171
 
02 Java Language And OOP PART II
Hari Christian
 
Java developer trainee implementation and import
iamluqman0403
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Conditional Statement
OXUS 20
 
Chap04
Terry Yoast
 
Programming fundamentals through javascript
Codewizacademy
 
UNIT 2 programming in java_operators.pptx
jijinamt
 
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Std 12 Computer Chapter 7 Java Basics (Part 2)
Nuzhat Memon
 
Introduction to Java
Ashita Agrawal
 
java basics - keywords, statements data types and arrays
mellosuji
 

Recently uploaded (20)

PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Ad

Lewis_Cocking_AP_Decision_Making_For_Coding

  • 1. 1 Program Statements  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
  • 2. 2 Program Development  The creation of software involves four basic activities: • establishing the requirements • creating a design • implementing the code • testing the implementation  The development process is much more involved than this, but these are the four basic development activities
  • 3. 3 Requirements  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
  • 4. 4 Design  A software design specifies how a program will accomplish its requirements  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  In object-oriented development, the design establishes the classes, objects, methods, and data that are required
  • 5. 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
  • 6. 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  Programmers often think erroneously that there is "only one more bug" to fix  Tests should consider design details as well as overall requirements
  • 7. 7 Flow of Control  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
  • 8. 8 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
  • 9. 9 The if Statement  The if statement has the following syntax: if ( condition ) statement; if is a Java reserved 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.
  • 10. 10 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 126)
  • 11. 11 Logic of an if statement condition evaluated false statement true
  • 12. 12 Boolean Expressions  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 (=)
  • 13. 13 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;  See Wages.java (page 130)  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
  • 14. 14 Logic of an if-else statement condition evaluated statement1 true false statement2
  • 15. 15 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 is called for by the Java syntax  For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements  See Guessing.java (page 132)
  • 16. 16 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  See MinOfThree.java (page 134)  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
  • 17. 17 Logical Operators  Boolean expressions can use the following logical operators: ! Logical NOT && Logical AND || Logical OR  They all take boolean operands and produce boolean results  Logical NOT is a unary operator (it operates on one operand)  Logical AND and logical OR are binary operators (each operates on two operands)
  • 18. 18 Logical NOT  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  Logical expressions can be shown using truth tables a !a true false false true
  • 19. 19 Logical AND and Logical OR  The logical AND expression a && b is true if both a and b are true, and false otherwise  The logical OR expression a || b is true if a or b or both are true, and false otherwise
  • 20. 20 Truth Tables  A truth table shows the possible true/false combinations of the terms  Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true true true true true false false true false true false true false false false false
  • 21. 21 Logical Operators  Conditions can use logical operators to form complex expressions if (total < MAX+5 && !found) System.out.println ("Processing…");  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
  • 22. 22 Short Circuited Operators  The processing of logical AND and logical OR is “short-circuited”  If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing…");  This type of processing must be used carefully
  • 23. 23 Truth Tables  Specific expressions can be evaluated using truth tables total < MAX found !found total < MAX && !found false false true false false true false false true false true true true true false false
  • 24. 24 Comparing Characters  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. 25 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)
  • 26. 26 Lexicographic Ordering  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. 27 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.");
  • 28. 28 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
  • 29. 29 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;
  • 30. 30 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;
  • 31. 31 Assignment Operators  There are many assignment operators, including the following: 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
  • 32. 32 Assignment Operators  The right hand side of an assignment operator can be a complex expression  The entire right-hand expression is evaluated first, then the result is combined with the original variable  Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);
  • 33. 33 Assignment Operators  The behavior of some assignment operators depends on the types of the operands  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 (+)
  • 34. 34 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
  • 35. 35 The while Statement  The while statement has the following syntax: while ( condition ) statement; while is a reserved word 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.
  • 36. 36 Logic of a while Loop statement true condition evaluated false
  • 37. 37 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  See Counter.java (page 143)  See Average.java (page 144) • A sentinel value indicates the end of the input • The variable sum maintains a running sum  See WinPercentage.java (page 147) • A loop is used to validate the input, making the program more robust
  • 38. 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 logical error  You should always double check to ensure that your loops will terminate normally  See Forever.java (page 148)
  • 39. 39 Nested Loops  Similar to nested if statements, loops can be nested as well  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 151)
  • 40. 40 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
  • 41. 41 The StringTokenizer Class  The default delimiters are space, tab, carriage return, and the new line characters  The nextToken method returns the next token (substring) from the string  The hasMoreTokens returns a boolean indicating if there are more tokens to process  See CountWords.java (page 155)
  • 42. 42 The for Statement  The for statement has the following syntax: for ( initialization ; condition ; increment ) statement; Reserved word The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration The condition-statement-increment cycle is executed repeatedly
  • 43. 43 The for Statement  A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }
  • 44. 44 Logic of a for loop statement true condition evaluated false increment initialization
  • 45. 45 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  See Counter2.java (page 157)  See Multiples.java (page 159)  See Stars.java (page 161)
  • 46. 46 The for Statement  Each expression in the header of a for loop is optional • 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  Both semi-colons are always required in the for loop header
  • 47. 47 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
  • 48. 48 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 • compute the average test score • determine the highest and lowest test scores • display the average, highest, and lowest test scores
  • 49. 49 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. 50 Program Development  Design – determine a possible general solution • Input strategy? (Sentinel value?) • Calculations needed?  An initial algorithm might be expressed in pseudocode  Multiple versions of the solution might be needed to refine it  Alternatives to the solution should be carefully considered
  • 51. 51 Program Development  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 164)
  • 52. 52 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  Carefully retest after finding and fixing an error
  • 53. 53 More Drawing Techniques  Conditionals and loops can greatly enhance our ability to control graphics  See Bullseye.java (page 169)  See Boxes.java (page 171)  See BarHeights.java (page 173)
  • 54. 54 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

Editor's Notes

  • #8: Note that the switch statement is not part of the AP subset and is not covered in the book.