Upload
francis-melton
View
230
Download
0
Embed Size (px)
DESCRIPTION
3 Logical Operators b Boolean expressions can also use logical operators: ! Logical NOT && Logical AND || Logical OR b operands and result are boolean
Citation preview
1
Boolean expressionsBoolean expressions truth tablestruth tables conditional operatorconditional operator switch statementswitch statement repetition statements:repetition statements:
• whilewhile• do/whiledo/while• forfor
Lecture 3Lecture 3
2
Boolean ExpressionsBoolean Expressions A condition often uses one of Java's A condition often uses one of Java's equality operators equality operators or or
relational operatorsrelational operators, which all return boolean results:, which all return boolean results:
==== equal toequal to!=!= not equal tonot equal to<< less thanless than>> greater thangreater than<=<= less than or equal toless than or equal to>=>= greater than or equal togreater than or equal to
Note the difference between the equality operator (Note the difference between the equality operator (====) and ) and the assignment operator (the assignment operator (==))
3
Logical OperatorsLogical Operators Boolean expressions can also use Boolean expressions can also use logical operatorslogical operators::
!! Logical NOTLogical NOT&&&& Logical ANDLogical AND|||| Logical ORLogical OR
operands and result are booleanoperands and result are boolean
4
Logical NOTLogical NOT logical negationlogical negation or or logical complementlogical complement
If boolean condition If boolean condition aa is true, then is true, then !a!a is false; if is false; if aa is false, is false, then then !a!a is true is true
Logical expressions can be shown using Logical expressions can be shown using truth tablestruth tables
a
truefalse
!a
falsetrue
5
Logical AND and Logical ORLogical AND and Logical OR Logical and:Logical and:
a && b
true if both true if both aa and and bb are true, and false otherwise are true, and false otherwise
Logical or:Logical or:
a || b
true if true if aa or or bb or both are true, and false otherwise or both are true, and false otherwise
6
Truth TablesTruth Tables A truth table shows the possible true/false combinations of A truth table shows the possible true/false combinations of
the termsthe terms Since Since &&&& and and |||| each have two operands, there are four each have two operands, there are four
possible combinations of true and falsepossible combinations of true and false
a
truetruefalsefalse
b
truefalsetruefalse
a && b
truefalsefalsefalse
a || b
truetruetruefalse
7
Logical OperatorsLogical Operators Conditions in selection statements and loops can use logical Conditions in selection statements and loops can use logical
operators to form complex expressionsoperators to form complex expressions
if (total < MAX && !found) System.out.println ("Processing…");
total < MAX
falsefalsetruetrue
found
falsetruefalsetrue
!found
truefalsetruefalse
total < MAX && !found
falsefalsetruefalse
8
More OperatorsMore Operators
increment and decrement operators: ++, --increment and decrement operators: ++, -- assignment operators: +=, *=, ...assignment operators: +=, *=, ... conditional operator conditional operator
9
Increment and Decrement Increment and Decrement OperatorsOperators
The The increment operatorincrement operator ( (++++) adds one to its operand) adds one to its operand The The decrement operatordecrement operator ( (----) subtracts one from its operand) subtracts one from its operand The statementThe statement
count++;
is essentially equivalent tois essentially equivalent to
count = count + 1;
10
Increment and Decrement Increment and Decrement OperatorsOperators Increment and decrement operators can be applied in:Increment and decrement operators can be applied in:• prefix formprefix form (before the variable) (before the variable) • postfix formpostfix form (after the variable) (after the variable)
When used alone in a statement, the prefix and postfix When used alone in a statement, the prefix and postfix forms are basically equivalent. That is,forms are basically equivalent. That is,
count++;
is equivalent tois equivalent to
++count;
11
Increment and Decrement Increment and Decrement OperatorsOperators ““prefix” and “postfix” refer to prefix” and “postfix” refer to whenwhen the value of the the value of the
variable gets incremented/decremented relative to when it variable gets incremented/decremented relative to when it is used in the expression.is used in the expression.• Prefix incrementPrefix increment: increment first, then use: increment first, then use• Postfix incrementPostfix increment: use, then increment: use, then increment• similarly with decrementsimilarly with decrement
12
Increment and Decrement Increment and Decrement OperatorsOperators Example: Suppose Example: Suppose count = 1. . Complete the following table:Complete the following table:
Statementx = count++x = ++countx = count--x = --count
count
x
13
Assignment OperatorsAssignment Operators Often we perform an operation on a variable, then store the Often we perform an operation on a variable, then store the
result back into that variableresult back into that variable Java provides Java provides assignment operatorsassignment operators to simplify that process to simplify that process For example, the statementFor example, the statement
num += count;
is equivalent tois equivalent to
num = num + count;
14
Assignment OperatorsAssignment Operators There are many assignment operators, including the There are many assignment operators, including the
following:following:
Operator
+=-=*=/=%=
Example
x += yx -= yx *= yx /= yx %= y
Equivalent To
x = x + yx = x - yx = x * yx = x / yx = x % y
15
Assignment OperatorsAssignment Operators The right hand side of an assignment operator can be a The right hand side of an assignment operator can be a
complete expressioncomplete expression The entire right-hand expression is evaluated first, then the The entire right-hand expression is evaluated first, then the
result is combined with the original variableresult is combined with the original variable ThereforeTherefore
result /= (total-MIN) % num;
is equivalent tois equivalent to
result = result / ((total-MIN) % num);
16
The Conditional OperatorThe Conditional Operator Java has a Java has a conditional operatorconditional operator that evaluates a boolean that evaluates a boolean
condition that determines which of two other expressions is condition that determines which of two other expressions is evaluatedevaluated
The result of the chosen expression is the result of the entire The result of the chosen expression is the result of the entire conditional operatorconditional operator
Its syntax is:Its syntax is:
condition ? expression1 : expression2
If the If the conditioncondition is true, is true, expression1expression1 is evaluated; if it is false, is evaluated; if it is false, expression2expression2 is evaluated is evaluated
17
The Conditional OperatorThe Conditional Operator The conditional operator is similar to an if-else statement, The conditional operator is similar to an if-else statement,
except that it is an expression that returns a valueexcept that it is an expression that returns a value
For example:For example:
larger = (num1 > num2) ? num1 : num2;
If If num1num1 is greater that is greater that num2num2, then , then num1num1 is assigned to is assigned to largerlarger; otherwise, ; otherwise, num2num2 is assigned to is assigned to largerlarger
The conditional operator is The conditional operator is ternaryternary, meaning that it , meaning that it requires three operandsrequires three operands
18
The switch StatementThe switch Statement The The switch statementswitch statement provides another means to decide provides another means to decide
which statement to execute nextwhich statement to execute next
The switch statement evaluates an expression, then The switch statement evaluates an expression, then attempts to match the result to one of several possible attempts to match the result to one of several possible casescases
Each case contains a (constant) value and a (possibly Each case contains a (constant) value and a (possibly empty) list of statementsempty) list of statements
The flow of control transfers to first statement in list The flow of control transfers to first statement in list associated with the first value that matches and continues associated with the first value that matches and continues thereonthereon
19
The switch StatementThe switch Statement The general syntax of a switch statement is:The general syntax of a switch statement is:
switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...
}
switchswitchandandcasecaseareare
reservedreservedwordswords
If If expressionexpressionmatches matches value2value2,,control jumpscontrol jumpsto hereto here
20
The switch StatementThe switch Statement Often a Often a break statementbreak statement is used as the last statement in each is used as the last statement in each
case's statement listcase's statement list
A break statement causes control to transfer to the end of A break statement causes control to transfer to the end of the switch statementthe switch statement
If a break statement is not used, the flow of control will If a break statement is not used, the flow of control will continue into the next casecontinue into the next case
Sometimes this can be helpful, but usually we only want to Sometimes this can be helpful, but usually we only want to execute the statements associated with one caseexecute the statements associated with one case
21
The switch StatementThe switch Statement A switch statement can have an optional A switch statement can have an optional default casedefault case
The default case has no associated value and simply uses the The default case has no associated value and simply uses the reserved word reserved word defaultdefault
If the default case is present, control will transfer to it if no If the default case is present, control will transfer to it if no other case value matchesother case value matches
Though the default case can be positioned anywhere in the Though the default case can be positioned anywhere in the switch, it is usually placed at the endswitch, it is usually placed at the end
If there is no default case, and no other value matches, If there is no default case, and no other value matches, control falls through to the statement after the switchcontrol falls through to the statement after the switch
22
The switch StatementThe switch Statement The expression of a switch statement must result in an The expression of a switch statement must result in an
integral data typeintegral data type, like an integer or character; it cannot be , like an integer or character; it cannot be a floating point valuea floating point value
Note that the implicit boolean condition in a switch Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with statement is equality - it tries to match the expression with a valuea value
You cannot perform relational checks with a switch You cannot perform relational checks with a switch statementstatement
See See http://www.csc.villanova.edu/~map/7000/progs/SwitchExample.javahttp://www.csc.villanova.edu/~map/7000/progs/SwitchExample.java
23
Repetition StatementsRepetition Statements Repetition statementsRepetition statements allow us to execute a statement allow us to execute a statement
multiple times repeatedlymultiple times repeatedly
They are often simply referred to as They are often simply referred to as loopsloops
Like conditional statements, they are controlled by boolean Like conditional statements, they are controlled by boolean expressionsexpressions
Java has three kinds of repetition statements: the Java has three kinds of repetition statements: the while while looploop, the , the do loopdo loop, and the , and the for loopfor loop
24
The while StatementThe while Statement The The while statementwhile statement has the following syntax: has the following syntax:
while ( condition ) statement;whilewhile is a is a
reserved wordreserved word
If the condition is true, the statement is executed.If the condition is true, the statement is executed.Then the condition is evaluated again.Then the condition is evaluated again.
The statement is executed repeatedly untilThe statement is executed repeatedly untilthe condition becomes false.the condition becomes false.
25
Logic of a while loopLogic of a while loop
statement
truetrue
conditionevaluated
falsefalse
26
The while StatementThe while Statement if condition of whileif condition of while statement is false initially, the statement is false initially, the
statement is never executedstatement is never executed
Therefore, the body of a while loop will execute zero or Therefore, the body of a while loop will execute zero or more timesmore times
See Counter.java (page 133)See Counter.java (page 133)
See Average.java (page 134)See Average.java (page 134)
See WinPercentage.java (page 136)See WinPercentage.java (page 136)
27
Infinite LoopsInfinite Loops The body of a whileThe body of a while loop must eventually make the loop must eventually make the
condition falsecondition false
If not, it is an If not, it is an infinite loopinfinite loop, which will execute until the user , which will execute until the user interrupts the programinterrupts the program
See Forever.javaSee Forever.java (page 138) (page 138)
28
Nested LoopsNested Loops Similar to nested if statements, loops can be nested as wellSimilar to nested if statements, loops can be nested as well
See See PPalindromeTesteralindromeTester..java java (page 137)(page 137)
29
The do StatementThe do Statement The The do statementdo statement has the following syntax: has the following syntax:
do{ statement;}while ( condition )
Uses bothUses boththe the dodo and andwhilewhile
reservedreservedwordswords
The statement is executed once initially, then the condition is evaluatedThe statement is executed once initially, then the condition is evaluated
The statement is repetitively executed until the condition becomes falseThe statement is repetitively executed until the condition becomes false
30
Logic of a do loopLogic of a do loop
truetrue
conditionevaluated
statement
falsefalse
31
The do StatementThe do Statement A do loop is similar to a while loop, except that the A do loop is similar to a while loop, except that the
condition is evaluated after the body of the loop is executedcondition is evaluated after the body of the loop is executed
Therefore the body of a do loop will execute at least one Therefore the body of a do loop will execute at least one timetime
See Counter2.javaSee Counter2.java (page 143)(page 143)
32
Comparing the while and do Comparing the while and do loopsloops
statement
truetrue
conditionevaluated
falsefalse
while loopwhile loop
truetrue
conditionevaluated
statement
falsefalse
do loopdo loop
33
The for StatementThe for Statement The The for statementfor statement has the following syntax: has the following syntax:
for ( initialization ; condition ; increment ) statement;
ReservedReservedwordword
The The initializationinitialization portion portionis executed onceis executed once
before the loop beginsbefore the loop begins
The statement isThe statement isexecuted until theexecuted until the
conditioncondition becomes false becomes false
The The incrementincrement portion is executed at the end of each iteration portion is executed at the end of each iteration
34
The for StatementThe for Statement A for loop is equivalent to the following while loop A for loop is equivalent to the following while loop
structure:structure:
initialization;while ( condition ){ statement; increment;}
35
Logic of a for loopLogic of a for loop
statement
truetrue
conditionevaluated
falsefalse
increment
initialization
36
The for StatementThe for Statement Like a while loop, the condition of a for statement is tested Like a while loop, the condition of a for statement is tested
prior to executing the loop bodyprior to executing the loop body Therefore, the body of a for loop will execute zero or more Therefore, the body of a for loop will execute zero or more
timestimes It is well suited for executing a specific number of times It is well suited for executing a specific number of times
that can be determined in advancethat can be determined in advance
See Counter3.javaSee Counter3.java (page 146)(page 146)
See Multiples.javaSee Multiples.java (page 147)(page 147)
See Stars.javaSee Stars.java (page 150)(page 150)
37
The for StatementThe for Statement Each expression in the header of a for loop is optionalEach expression in the header of a for loop is optional
• If the initialization is left out, no initialization is performedIf the initialization is left out, no initialization is performed• If the condition is left out, it is always considered to be true, and If the condition is left out, it is always considered to be true, and
therefore creates an infinite looptherefore creates an infinite loop• If the increment is left out, no increment operation is performedIf the increment is left out, no increment operation is performed
Both semi-colons are always required in the for loop headerBoth semi-colons are always required in the for loop header
38
Program DevelopmentProgram Development The creation of software involves four basic activities:The creation of software involves four basic activities:
• establishing the requirementsestablishing the requirements• creating a designcreating a design• implementing the codeimplementing the code• testing the implementationtesting the implementation
The development process is much more involved than this, The development process is much more involved than this, but these basic steps are a good starting pointbut these basic steps are a good starting point
39
RequirementsRequirements RequirementsRequirements specify the tasks a program must accomplish specify the tasks a program must accomplish
(what to do, not how to do it)(what to do, not how to do it) They often include a description of the user interfaceThey often include a description of the user interface An initial set of requirements are often provided, but An initial set of requirements are often provided, but
usually must be critiqued, modified, and expandedusually must be critiqued, modified, and expanded It is often difficult to establish detailed, unambiguous, It is often difficult to establish detailed, unambiguous,
complete requirementscomplete requirements Careful attention to the requirements can save significant Careful attention to the requirements can save significant
time and money in the overall projecttime and money in the overall project
40
DesignDesign An An algorithmalgorithm is a step-by-step process for solving a problem is a step-by-step process for solving a problem A program follows one or more algorithms to accomplish A program follows one or more algorithms to accomplish
its goalits goal The The designdesign of a program specifies the algorithms and data of a program specifies the algorithms and data
neededneeded In object-oriented development, the design establishes the In object-oriented development, the design establishes the
classes, objects, and methods that are requiredclasses, objects, and methods that are required The details of a method may be expressed in The details of a method may be expressed in pseudocodepseudocode, ,
which is code-like, but does not necessarily follow any which is code-like, but does not necessarily follow any specific syntaxspecific syntax
41
ImplementationImplementation ImplementationImplementation is the process of translating a design into is the process of translating a design into
source codesource code Most novice programmers think that writing code is the Most novice programmers think that writing code is the
heart of software development, but it actually should be the heart of software development, but it actually should be the least creative stepleast creative step
Almost all important decisions are made during Almost all important decisions are made during requirements analysis and designrequirements analysis and design
Implementation should focus on coding details, including Implementation should focus on coding details, including style guidelines and documentationstyle guidelines and documentation
See ExamGrades.javaSee ExamGrades.java (page 155)(page 155)
42
TestingTesting A program should be executed multiple times with various A program should be executed multiple times with various
input in an attempt to find errorsinput in an attempt to find errors DebuggingDebugging is the process of discovering the cause of a is the process of discovering the cause of a
problem and fixing itproblem and fixing it Programmers often erroneously think that there is "only Programmers often erroneously think that there is "only
one more bug" to fixone more bug" to fix Tests should focus on design details as well as overall Tests should focus on design details as well as overall
requirementsrequirements