PowerPoint Presentation - Chapter 6 Control Statements

Download Report

Transcript PowerPoint Presentation - Chapter 6 Control Statements

Chapter 6
Boolean Variables & Nested Loops
Go
Section 1 - Review of Logical & Relational Operators
Go
Section 2 - Simple & Compound Boolean Expressions
Go
Section 3 - Truth Tables
Go
Section 4 - String Methods: trim, length, & compareTo
Go
Section 5 - Boolean Variables
Go
Section 6 - Nested For and While Loops
Go
Section 7 - Software Systems
1
Chapter 6 Section 1
Review of Logical and Relational Operators
2
6.1 Logical Operators
Logical operators are used with if, while, and for statements to
control the order of execution.
Logical Operators allow us to modify simple boolean expressions or
combine simple boolean expressions into compound ones. These are
the three logical operators:
Operator
Relationship
!
Not
&&
And
||
Or
Do not place a space between the operators that use
two symbols … && and | |
3
6.1 Relational Operators
Relational operators are used to form simple Boolean Expressions.
Here are the six relational operators:
Operator
Relationship
==
equal to
!=
not equal to
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
Do not place a space between the operators that use
two symbols … >= <= == or !=
4
6.1 Precedence Rules for Java Operators
Operator
Symbol
Precedence Level
Association
( )
1
---------
Method Selector
.
2
left to right
Unary Minus
-
3
---------
Unary Plus
+
3
---------
Not
!
3
---------
new
3
right to left
Casting
(int)
(double)
3
right to left
Division
/
4
left to right
Multiplication
*
4
left to right
Mod or Remainder
%
4
left to right
Subtraction
-
5
left to right
Addition
+
5
left to right
6
---------
Parentheses
Construction
Relational Operators
== !=
< <= > >=
And
&&
8
left to right
Or
||
9
left to right
= += -= *= /= %=
10
right to left
Assignment
5
Chapter 6 Section 2
Review of Simple and Compound
Boolean Expressions
6
6.2 Simple Boolean Conditions
The ! (“NOT”) operator can be applied to a simple boolean condition
or a boolean variable. Here it is applied to a simple boolean expression:
if ( ! (grade > 59) )
System.out.println(“Your grade is an F”);
When applied to a boolean variable or expression, ! changes the
overall value to the opposite value.
In the boolean expression above, if grade > 59 evaluates to true,
then ! (grade > 59) evaluates to false.
In the boolean expression above, if grade > 59 evaluates to false,
then ! (grade > 59) evaluates to true.
7
6.2 Compound Boolean Expressions
The && and || operators are used to form compound boolean
expressions.
&& (referred to as “AND”)
| | (referred to as “OR”)
We have looked at these examples before:
if (grade >= 90 && grade <= 100)
System.out.println (“Your grade is A”);
if (grade < 0 | | grade > 100)
System.out.println (“Grade not possible.”);
8
6.2 Extended Ifs with
Simple Boolean Expressions
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else if (testAverage >= 70)
System.out.print(“Grade is C. ”);
else if (testAverage >= 80)
The order of this
extended if
statement is
problematic because
if testAverage holds
the value 93, then
“Grade is D.” will be
printed.
System.out.print(“Grade is B. ”);
else if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else
System.out.print(“Grade is F. ”);
If we change the conditions of
the extended-if so that it
contains compound boolean
expressions, then the order of
the branches doesn’t matter
and we can guarantee the
accuracy of an extended if.
9
6.2 Extended if Statements
with compound boolean expressions
Here is the rewritten extended-if where the order of the branches
doesn’t matter, because compound boolean expressions are used in
the test conditions.
if (testAverage >= 70 && testAverage < 80)
System.out.print(“Grade is C. ”);
else if (testAverage >= 80 && testAverage < 90)
System.out.print(“Grade is B. ”);
else if (testAverage >= 90 && testAverage <= 100 )
System.out.print(“Grade is A. ”);
However, having an
un-logical order to
the branches as
seen here makes the
code less readable
and more difficult to
verify.
else if (testAverage >= 60 && testAverage < 70)
System.out.print(“Grade is D. ”);
else
System.out.print(“Grade is F. ”);
10
6.2 Extended if Statements
with compound boolean expressions
Here is the rewritten extended-if where the order of the branches
doesn’t matter, because compound boolean expressions are used in
the test conditions.
if (testAverage >= 90 && testAverage <= 100)
System.out.print(“Grade is A. ”);
else if (testAverage >= 80 && testAverage < 90)
System.out.print(“Grade is B. ”);
This order is much more
logical and adds to the
readability of the code.
else if (testAverage >= 70 && testAverage < 80)
System.out.print(“Grade is C. ”);
else if (testAverage >= 60 && testAverage < 70)
System.out.print(“Grade is D. ”);
else
System.out.print(“Grade is F. ”);
11
Chapter 6 Section 3
Truth Tables
12
6.3 Truth Tables
Truth tables are essential tools for helping us verify the accuracy of
logical expressions, whether they are simple or compound.
For compound boolean expressions involving logical operators, truth
tables show how the value of the overall expression depends on the
values of the operands. Here, the operands are A and B.
•
With two operands we must consider all four possible
combinations of values that A and B can have to know what the
expression A && B will evaluate to.
Here is a truth table that
shows the results of
evaluating A && B.
13
6.3 Truth Table for A && B
Two operands, A and B. Four
possible outcomes for A && B
depending on the four possible
combinations of true and false.
The operands A or B can be
simple boolean expressions,
like x > 0.
The truth table shows you the following results:
If A is true and B is true, then A && B evaluates to true.
If A is true and B is false, then A && B evaluates to false.
If A is false and B is true, then A && B evaluates to false.
If A is false and B is false, then A && B evaluates to false.
Notice that for A && B to evaluate to true, both and A and B must be
true individually.
14
6.3 Truth Table for A && B
Here is why this is important. You can assume that A and B are
simple boolean expressions like:
A is grade >= 90 and
B is grade <= 100
You could then use a truth table to verify the results of an if condition
like:
if (grade >= 90 && grade <= 100) when grade holds the value 95.
This helps verify that the code is correct when various values are tested.
15
6.3 Truth Table for A || B
Two operands, A and B.
Four possible outcomes
for A || B depending on
the four possible
combinations of true
and false.
The truth table shows you the following results:
If A is true and B is true, then A || B evaluates to true.
If A is true and B is false, then A || B evaluates to true.
If A is false and B is true, then A || B evaluates to true.
If A is false and B is false, then A || B evaluates to false.
Notice that A || B is false, only when both A and B are individually
false.
16
6.3 Truth Table for ! A
One operand, A. Two possible
outcomes for ! A depending on
the two possible values of true and
false.
The truth table shows you the following results:
If A is true, then ! A evaluates to false.
If A is false, then ! A evaluates to true.
17
6.3 Possible Combinations in Truth Tables
If there are n operands, then there are 2n combinations of true and
false.
So if there is one operand (like the expression ! A) , there are two
possible values of true and false … 21 = 2.
If there are 2 operands (like A && B) , there are 4 possible
combinations of true and false, and there are 4 possible results …
22 = 4.
If there are 3 operands (like A && B && C), there are 8 possible
combinations of true and false, and there are 8 possible results …
23 = 8.
If there are 4 operands (like A || B || C || D), there are 16 possible
combinations of true and false, and there are 16 possible results …
24 = 16.
18
6.3 Short-Circuit Evaluation using &&
•
In Java, the JVM may know the result of a compound Boolean
expression before evaluating all of its parts. Most compilers and
systems allow this and will stop evaluation as soon as the result is
known. This is called short-circuit evaluation.
•
If the first operand A is false and the second operand B is true as in
if( A && B ) …
then the JVM knows the entire condition is false once it sees the
first operand is false because && is being used and Java knows
that both operands must be true for the entire expression to be true.
So the second operand B is not examined at all!
19
6.3 Short-Circuit Evaluation using ||
•
For the OR operator ||, if the first operand A is true and the second
operand B is false as in
if( A || B )
…
then the JVM knows the entire condition is true once it sees the
first operand is true because the OR operator || is being used and
Java knows that only one operand must be true for the entire
expression to be true. So the second operand is not examined at
all.
20
6.3 Utilizing Short-Circuit Protections
This code takes advantage of short-circuit evaluation:
Scanner reader = new Scanner(System.in);
int count, sum;
System.out.print(“Enter the count: ”);
count = reader.nextInt();
System.out.print(“Enter the sum: ”);
sum = reader.nextInt();
if (count > 0 && sum/count > 10) // count > 0 must be first for this to work!
System.out.println(“average > 10”);
else
System.out.println(“count = 0 or average <= 10”);
Note: if count is <= 0, the second part of the boolean expression is NOT
evaluated and in particular, if count was 0, then the expression is
protected against division by zero.
21
6.3 DeMorgan’s Law
DeMorgan’s Law helps define some useful Boolean equivalences.
For instance, the following pairs of Boolean expressions are
equivalent as truth tables readily confirm. The first two are what
are called DeMorgan’s Law.
! (A || B)
equivalent to !A && !B
! (A && B)
equivalent to !A || !B
You only need
to remember
these two.
A || (B && C) equivalent to (A || B) && (A || C)
A && (B || C) equivalent to (A && B) || (A && C)
22
6.3 Avoid Complicated Logic
Its best to avoid complicated logical expressions, because they
can be difficult to prove even with a truth table. For example:
if (A || B && C)
or
if (A && B || C)
however you might need to use logic that says that four
different things must be true before a segment of code is
executed or any of four different things must be false
before a segment of code is executed. You completed
code like this in the program RectangleDrawer.
if (x < 0 || y < 0 || width < 1 || height < 1)
JOptionPane.showMessageDialog(“null”, “You entered …
23
Chapter 6 Section 4
The String Methods
trim(), length(), and compareTo()
24
6.4 The String Method trim()
The String class has a method named trim. When a trim message is
sent to a string, a new string that contains no leading or trailing blank
spaces is returned.
Example:
System.out.print(“Enter a name: ”);
String name = reader.nextLine();
// if the following is entered from the keyboard: “
Jill
”
// then if we printed it out with …
System.out.println(name);
we would see in the output window …
“
Jill
”
However, (see next slide) ….
25
6.4 The String Method trim()
If the code was …
System.out.print(“Enter a name: ”);
String name = reader.nextLine();
// and again we enter from the keyboard: “
Jill
”
// and then we use the following lines of code:
name = name.trim(); // trim the value in name and restore in name
System.out.println(name);
then we would see in the output window …
“Jill”
Again, when we call name.trim(); the String value in name is trimmed
and a new String value is created and returned. By restoring the new
value that is returned back into name, then the old value in name is
overwritten (deleted).
26
6.4 The String Method length()
We learned earlier this year that the length ( ) method returns the
number of characters in a String object. Example:
System.out.print(“Enter a name: ”);
String name = reader.nextLine();
int length = name.length();
System.out.println(length);
If nothing is entered from the keyboard, not even a blank space, and
the return/enter key is pressed, then the variable length would hold the
value zero.
Therefore, we can also stop a while ( ! done ) loop if we use an if
statement to test whether length holds the value zero as follows:
if (name.length() == 0)
done = true;
27
6.4 The String Method compareTo()
int compareTo (String other) <--- from the Java API
The string method compareTo can be used to check to see if the contents of
two String objects are equal, in other words to see if they contain exactly the
same characters. Example:
String name = reader.nextLine();
if ( name.compareTo(“Bill”) == 0)
System.out.println(“The names are equal.”);
else
System.out.println(“The names are NOT equal.”);
If “Bill” is entered from the keyboard, then obviously the output will be:
“The names are equal.”
You cannot use: if ( name == “Bill” )
You cannot use the == operator to see if
two strings contain exactly the same
characters. == checks to see if two
string variables point at the same string
object, not that the contents of the two
strings are equivalent.
28
6.4 Using compareTo() to Check Inequality
You can also test to see if two strings are unequal by using != as
follows:
String name = reader.nextLine();
if ( name.compareTo(“Bill”) != 0)
System.out.println(“The name entered is not Bill.”);
else
System.out.println(“The name is Bill.”);
You can see what the output would be depending on what is entered.
29
Chapter 6 Section 5
Boolean Variables
30
6.5 Boolean Variables
•
•
Boolean variables can hold a value of true or false.
A boolean is a primitive data type like int, double, or char.
Example:
boolean startGame = true;
if ( startGame ) // there is no reason to use (startGame == true)
{
// but you can
… code that sets up and starts the game
}
Java will simply inspect the boolean value inside startGame and
decide whether to run the code in the if branch based on its value.
31
6.5 Unintended Boolean Assignments
It is easy to make the mistake of using = when you mean ==. This is
another reason why you should NOT use …
if (startGame == true)
because if you accidentally coded …
if (startGame = true)
Eclipse and other compilers will
not show a syntax or compile
error when you do this!
// this assigns true to the variable startGame
When startGame holds the value false, then you have just given
startGame the value true when you didn’t want to. This would give
erroneous results in a program where you don’t want to execute
the lines of code in the if statement when startGame is false.
What is important to realize is that if (startGame = true) doesn’t
give a syntax error in Java. Java lets you do this for boolean
variables but not for other variables. See the demo program for this.
32
6.5 Boolean Variable Use Example
boolean done = false;
int sum = 0;
// note that since done is false … ! false equals true and the loop runs
while (! done)
{
System.out.print(“Enter a value to sum: ”);
int x = reader.nextInt();
sum += x;
reader.nextLine();
// consume newline character
System.out.print (“Type Y to continue or N to stop (Y/N): ”);
String ans = reader.nextLine();
if ( ! (ans.compareTo(“Y”) == 0) ) // if ans is not equal to Y stop.
done = true; // while (! true) will stop the loop since ! true = false
}
Note: when checking to see if two strings are equal, we can’t use ==.
We must call the compareTo() method of the String class.
33
6.5 Compound Boolean Example
Assume factory company XYZ gives two tests to prospective
employees to see if they are qualified for any of three levels of
positions. The company has jobs available in these areas:
managerial, supervisory, and line worker.
For a person to qualify for a management level position, they must
score above 90 on both tests.
For a person to qualify for a supervisory level position, they must
score above 90 on at least one of the tests.
For a person to qualify for a line worker level position, they must
score above 70 on at least one of the tests and they must not
score below 50 on either one of the tests.
34
6.5 Compound Boolean Example
If score1 and score2 are two variables that hold the results of the two
tests for a prospective employee, then how could we write the code
using an if statement to properly test the values of both scores so it
can be determined what positions they are qualified for?
35
6.5 Compound Boolean Example
If score1 and score2 are two variables that hold the results of the two
tests for a prospective employee, then how could we write the code
using an if statement to properly test the values of both scores so it
can be determined what positions they are qualified for?
if ( score1 >= 90 && score2 >= 90)
System.out.println(“Qualified to be a Manager.”);
if ( score1 >= 90 || score2 >= 90)
System.out.println(“Qualified to be a Supervisor.”);
if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50))
System.out.println(“Qualified to be a Line Worker.”);
36
6.5 Priority of Logical Operators
You can use parentheses with complex expressions as seen on the
last slide. Obviously, expressions in parentheses are evaluated
first.
In the expression below what is executed first?
the && or the ! ???
if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50))
System.out.println(“Qualified to be a Line Worker.”);
37
6.5 Priority of Logical Operators
You can use parentheses with complex expressions as seen
previously. Obviously, expressions in parentheses are evaluated
first.
In the expression below what is executed first?
the && or the ! ???
Answer: the ! (Not)
if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50))
System.out.println(“Qualified to be a Line Worker.”);
38
6.5 Code Without Boolean Variables
Scanner reader = new Scanner (System.in);
System.out.print(“Enter the first test score: ”);
int score1 = reader.nextInt();
System.out.print(“Enter the second test score: ”);
int score2 = reader.nextInt();
So let’s review the
code again and see
how it might be made
better by using
boolean variables.
if ( score1 >= 90 && score2 >= 90)
System.out.println(“Qualified to be a Manager.”);
if ( score1 >= 90 || score2 >= 90)
System.out.println(“Qualified to be a Supervisor.”);
if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50))
System.out.println(“Qualified to be a Line Worker.”);
39
6.5 Code Without Boolean Variables
The last if statement on the previous slide allows us to give a great
example of DeMorgan’s Law. The final part of the boolean condition
below ….
if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50))
System.out.println(“Qualified to be a Line Worker.”);
! (score1 < 50 || score2 < 50))
can also be written as …
(score1 >= 50 && score2 >= 50))
40
6.5 Code With Boolean Variables
By using boolean variables, we can make the code much
easier to read and understand, plus the variables may be
used later on in different lines of code for other purposes if
desired.
However, it requires a little more coding. We need to declare
some boolean variables and then give them values.
(See next two slides)
41
6.5 Code With Boolean Variables
boolean bothHigh, atLeastOneHigh,
atLeastOneModerate, noLow;
….. // input code as before
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = ! (score1 < 50 || score2 < 50);
Any of the expressions on the right can be changed if necessary
without changing any other code and the program will work as
intended. For example, we might want to change the 50s to 60, the 70s
to 80, and the 90s to 95. Now let’s substitute on the next slide
42
6.5 Code With Boolean Variables
Look how nice and readable the code becomes when we use
the boolean variables.
if (bothHigh)
System.out.println(“Qualified to be a Manager.”);
if (atLeastOneHigh )
System.out.println(“Qualified to be a Supervisor.”);
if (atLeastOneModerate && noLow )
System.out.println(“Qualified to be a Clerk.”);
43
6.5 Second Example of Boolean Variables
String day = reader.nextLine();
boolean weekday = day.compareTo(“Monday”) == 0 ||
day.compareTo(“Tuesday”) == 0 ||
day.compareTo(“Wednesday”) == 0 ||
day.compareTo(“Thursday”) == 0 ||
day.compareTo(“Friday”) == 0;
if (weekday )
System.out.println(“The day is a weekday”);
Code similar to this will be used on the Birthday Month program.
44
6.5 Precedence Rules for Logical Operators
•
Don’t forget the precedence rules for
Logical Operators
•
! has the highest precedence & the same precedence
as the other unary operators plus and minus … + -.
•
&& and || only have higher precedence than the
assignment operators.
•
&& has higher precedence than ||.
45
6.5 Precedence Rules for Java Operators
Operator
Symbol
Precedence Level
Association
( )
1
---------
Method Selector
.
2
left to right
Unary Minus
-
3
---------
Unary Plus
+
3
---------
Not
!
3
---------
new
3
right to left
Casting
(int)
(double)
3
right to left
Division
/
4
left to right
Multiplication
*
4
left to right
Mod or Remainder
%
4
left to right
Subtraction
-
5
left to right
Addition
+
5
left to right
6
---------
Parentheses
Construction
Relational Operators
== !=
< <= > >=
And
&&
8
left to right
Or
||
9
left to right
= += -= *= /= %=
10
right to left
Assignment
46
6.5 Invalid Conjunction Code
Don’t forget … in algebra, we might write a conjunction as:
0 < x < 20 but we cannot do this in Java
We cannot do that in Java, C++, or most other languages. We must
write a compound boolean expression as follows:
(x > 0) && (x < 20)
Note the convention is to place x first in both simple boolean
expressions. You should practice doing it this way.
47
6.5 Using Boolean Variables to Control Loops
Notice how the boolean variable done is used to start and end the loop
appropriately. This loop continues until the user enters an 8 letter
word.
boolean done = false;
while ( ! done )
{
System.out.print("Enter a word that you think has 8 letters: ");
String word = reader.nextLine();
if (word.length() == 8)
{
System.out.println("The word " + word + " has 8 letters in it. This loop is over.");
done = true;
}
else
{
System.out.println("The word " + word + " does NOT have 8 letters in it.");
System.out.println();
}
}
48
Chapter 6 Section 6
Nested For and While Loops
49
6.6 Using Loop Control Variables i and j
It has been traditional for over 50 years to use i, j, and k as loop
control variables. This stems from the fact that programmers
might have more than one loop in a program and you couldn’t
use a variable multiple times like modern languages. So
programmers would always use i for their first loop control
variable, j for their second loop lcv, and k for their third loop lcv,
etc. They also liked using one letter loop control variables,
because it cut down on typing, especially when punch cards were
used.
It turns out we will use I and j for loop control variables when we have
nested loops. You’ll see shortly.
50
6.6 Nested Loop Structures
Many problems can be solved by placing one loop inside of another
loop.
If we place one loop inside of another loop, then we call it a nested
loop structure.
How could we write a nested for loop structure that would print the
following numbers in rows and columns as seen here using a
printf statement:
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
51
6.6 Nested Loop Example & Output
We could use this code:
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 5; j++)
{
System.out.printf("%5d", j);
}
System.out.println();
}
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
Notice that the outside loop
runs four times and the inside
loop runs five times.
Observing the output, you
notice there are four rows and
five columns.
So it should be evident that the
outside loop controls the
number of rows and the inside
loop controls the number of
columns.
So since the outside loop runs
four times … there are 4 rows.
Since the inside loop runs five
times … there are 5 columns.
A crucial element to making this
print in rows and columns is the
System.out.println(); statement
after the inside loop! It can’t be
in the printf statement.
52
6.6 Nested Loop Example & Output
Think about the values of i and j as the
loop runs.
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 5; j++)
{
System.out.printf("%5d", j);
}
System.out.println();
}
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
When the outside loop runs the
first time when i is 1, the inner
loop will run three times first
when j = 1, then j = 2, and then
j = 3.
When the outside loop runs the
second time when i is 2, the
inner loop will run three times
with j = 1, j = 2, and then j = 3.
When the outside loop runs the
third time when i is 3, the inner
loop will run three times with j =
1, j = 2, and then j = 3.
When the outside loop runs the
fourth time when i is 4, the inner
loop will run three times with j =
1, j = 2, and then j = 3.
53
6.6 Nested Loop Example 2
Here is a second example of a nested loop structure:
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 3; j++)
{
System.out.printf("%5d", i);
}
System.out.println();
}
1
2
3
4
5
6
1
2
3
4
5
6
1
2
3
4
5
6
54
6.6 Nested Loop Example 3
Here is a third example of a nested loop structure:
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 8; j++)
{
System.out.printf("%5d", i + j);
}
System.out.println();
}
2
3
4
5
6
7
8
9
3
4
5
6
7
8
9 10
4
5
6
7
8
9 10 11
5
6
7
8
9 10 11 12
6
7
8
9 10 11 12 13
55
6.6 Nested Loop Example 4
Here is a fourth example of a nested loop structure:
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 3; j++)
{
System.out.printf("%5d", 2 * i + j);
}
System.out.println();
}
3
4
5
5
6
7
7
8
9
9 10 11
56
6.6 Triangular Nested Loop Example 1
This is a triangular nested loop structure, because of the use of the
outside loop control variable i in the inside loop header.
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print('*');
}
System.out.println();
}
Notice the use of j
<= i in the nested
loop and a printf
is not used.
*
**
***
****
57
6.6 Triangular Nested Loop Example 2
Here is a second example of a triangular nested loop structure.
Notice the extended if needed to control the formatting before the
inside loop.
for(int lines = 1; lines <= 4; lines++)
{
// use a field width of 5 - lines to right justify a blank space
if (lines == 1)
System.out.printf("%4s", " "); // 5 - 1 = 4
else if (lines == 2)
System.out.printf("%3s", " "); // 5 - 2 = 3
else if (lines == 3)
System.out.printf("%2s", " "); // 5 - 3 = 2
else if (lines == 4)
System.out.printf("%1s", " "); // 5 - 4 = 1
*
***
*****
*******
for(int stars = 1; stars <= 2 * lines - 1; stars++)
System.out.print ('*');
System.out.println();
}
58
6.6 Testing Loops
•
Loops increase the difficulty of testing, because
– They often do not iterate a fixed number of times
– We need to design test data to cover situations where the loop
iterates:
• zero times, one time, and multiple times
Whether there is just one loop or a nested loop structure, we need to
be careful how we design our loops and then some testing should
be done.
This means that when checking the design of a loop either by
reviewing the code or running test data, you should check the
following:
1. entry
conditions of the loop
2. exit conditions of the loop
3. The number of loop iterations
59
6.6 Printing Proper Divisors
How can we print all of the proper divisors of a number? A positive
proper divisor is a positive divisor of an integer, excluding itself.
For example: 1, 2, and 3 are positive proper divisors of 6, but 6
itself is not.
System.out.print(“Enter a positive integer: ”);
int n = reader.nextInt();
for (int divisor = 1; divisor < n; divisor++)
{
if ( n % divisor == 0)
System.out.println( divisor);
}
You need to stop and think
about the kind of test data you
need to use to fully test your
code. What integers can be
entered for n so that the loop
will run 0, 1, and multiple
times?
Remember n is not
considered a proper divisor of
itself.
60
6.6 Nested Loops with Boolean Variables
It is possible to control nested while loops that are controlled by
boolean variables. You can see the overall design here, but a full
example is given you in the LoopsWithBooleanVarsDemo program.
boolean quit = false;
while ( ! quit )
{
System.out.println (”Welcome to the Guessing Game.");
boolean done = false;
while ( ! done )
{
… code for game that eventually sets done to true
}
System.out.print("Enter \"quit\" to quit this game or \"no\" to continue: ");
String answer = reader.nextLine();
if (answer.compareTo ("quit") == 0)
quit = true;
} // end of while ( ! quit) loop
61
6.6 Loop Verification
In designing and implementing loops, it is the responsibility of a
programmer to verify that a loop will do what it is suppose
to do.
In other words, a programmer should provide loop verification
by making statements about a loop that should be true
when a loop is entered and when it is exited. Also, other
statements can be made about how a loop works.
62
6.6 Input & Output Assertions
You are expected to know what an input assertion and output
assertion is for the AP exam. These terms refer to loop
verification:
1.
Input assertions state what should be true before a loop
is entered.
2.
Output assertions state what should be true when a
loop is exited.
63
6.6 Loop Variants & Invariants
Two other terms are:
1.
A Loop invariant is an assertion that expresses a
relationship (between variables) that remain constant
throughout all iterations of a loop. In other words, it is a
statement that is true both before the loop is entered
and after each iteration of the loop.
2.
A Loop variant is an assertion whose truth changes
between the first and final execution of the loop. The
loop variant expression should be stated in such a way
that it guarantees the loop is exited.
64
Chapter 6 Section 7
Software Systems
65
6.7 What are Software Systems?
•
In the real world, software systems are large programs that
are designed and maintained by a group of programmers,
not a single individual.
•
After the design phase, a team of programmers are
assigned various components to implement for a system
being created because they would be unable to write all of
the code by themselves. So a system is made up of
software components.
66
6.7 Information Hiding
•
The specifications for a software component contain the
name of the class and the name of the methods, plus any
other vital information needed to be able to call the
methods.
•
If a programmer adheres strictly to the specifications, we
don’t care how the code is written just so it doesn’t contain
compile-time or logic errors. We trust that whoever wrote
the code made it efficient.
67
6.7 The Quality of Software Systems
•
There are several measures of software quality, such as
readability, maintainability, robustness and
correctness.
•
Overall a Software System must be reliable meaning
that it should contain all of the above characteristics to a
high degree, but it is only reliable if the model designed and
built by the programmers represents the software that was
requested to be made.
68
6.7 Readability of Program Code
•
Readability refers to the ability of any programmer to be
able to easily read and understand the code in a program.
Readability is dependent on choosing good method and
variable names, as well as, indentation and spacing. The
method and variable names should be self-describing.
69
6.7 Maintainability of Program Code
•
Maintainability refers to the ability of programmers to be
able to easily maintain the code in a program. This means it
should be easy to update the code by adding or deleting
portions of it without significantly changing the overall
design.
70
6.7 Robustness of Program Code
•
A program should be robust.
•
A Robust program tolerates errors in user inputs and
recovers gracefully without halting the program. (You
will learn some of the ways to do this in different ways in
the near future.)
•
The best and easiest way to write robust programs is to
check user inputs immediately on entry and reject
invalid user inputs by giving them feedback through
error messages.
71
6.7 Correctness of Program Code
•
Finally, Correctness refers to whether the code of a
program is written correctly without any logic errors and
does the code implement the functionality of the program the
way that it was intended.
72