Download Switch expression must be of type int or char

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 7 Logic and Selection
H. W. p. 248 #1, 2, 3, 6, 7, 9
Objectives
To explore the concept of selection and the need for
selection control structures
To examine the if instruction in its two basic forms: if-then
and if-then-else
To emphasize the need for proper indentation styles an use
of braces in control structures.
To examine Java facilities for constructing relational
expressions, including == and != for all data types and <. <=,
>, and >= for primitive types.
To explore the forms of Boolean expressions that are
supported by Java, especially the AN (&&), OR (||), and NOT
(!) operations
To introduce the concept of conditional (short-circuit)
evaluation an how it is used to avoid certain run-time errors
To examine the boolean data type and illustrate how it is
used in methods (predicates), variables, and parameter
passage
To introduce the discipline of logic and explore how logical
reasoning and logical rules can be used to improve Boolean
expressions
To revisit the notion of assertions, examine the form of
assertions that involve selections, and suggest a method for
assertion testing.
To examine how if instructions can be nested and used as
multiway selection instructions, including cascading
conditions
To introduce the switch instruction
To introduce testing concepts and how logic plays a
significant role in both functional testing and structural
testing
Computer science is a mathematical discipline.
Much of what we write in programs and most of what is
executed on a computer is based on formal logic.
7.1 The if instruction
Java provides two selection instructions, the if and the
switch.
The if instruction has two formats: the if-then-else format
the if-then format
The if-then-else format
if ( customerAge < 3 ) { // the condition
mealCost = 0;
// the then clause
} else {
mealCost = 12;
// the else clause
}
The if-then format
if ( customerAge < 3 ) { // the condition
mealCost = 0;
// the then clause
}
Selection instructions are in the category of control
structures because they control the order in which
statements execute.
See Figure 7.2 on page 214 for if-then-else instruction
and Figure 7.5 on page 217 for the if-then instruction
7.2 Relational Expressions
Boolean logic and Boolean expressions
When a Boolean expression evaluates, the result is a
logical or boolean value, true or false.
Note the difference between Boolean and boolean
Relational Expressions are used for to compare two
expressions of compatible type
relational expressions evaluate to a boolean value
== equality
!= not equal
<
|
<=
|
<
| these require operand types to be primitive
>=
|
Format is
operand1 operator operand2
Note difference between value equality and identity
equality (reference types compare bindings).
7.3 Boolean expressions
Java Boolean expressions have a format similar to that
above
i.e. operand1 operator operand2
Boolean expressions evaluate to a boolean type value
(true or false)
Java Boolean operators
equal operator ( == )
not equal operator ( != )
NOT operator ( ! )
AND operator ( && )
OR operator ( || )
The first two operators are the same relational operators
above.
Evaluating a Boolean expression
Can use just true or false.
e.g. boolean b = true;
If the expression is more complex, a truth table is a good
way to determine the result of the expression.
boolean c = ( a || b );
operand1
operand 2
operand1 || operand2
--------------------------------------------------------------------false
false
false
false
true
true
true
false
true
true
true
true
Note the precedence of selected int and Boolean
operators in Figure 7.12
High
mid
low
lower2
lower3
lower4
lower5
-++
-++
!
/
*
%
+
<
<=
>
>=
==
!=
&&
||
posfix
prefix
7.4 Conditional Evaluation
Evaluation of Boolean AND and OR operators.
Short-circuit evaluation
If the left operand of an AND expression is false, then the
result will be false no matter what the right operand’s
value is. Hence the right operand is ignored.
if the left operand of an OR expression is true, then the
result will be true no matter what the right operand’s value
is. Hence the right operand is ignored.
Example used for this is to guard against run time error,
such as division by zero.
If ( totalPoints != 0 and scorePoints > 50)
{
score = scorePoints / total Points;
}
7.5 Predicates
Methods that return a boolean value are called predicates.
e.g. the isVowel predicate
if ( isVowel(character) )
{
System.out.println( “Character is a vowel.”);
}
7.6 Nesting if instructions
“Careful discipline in consistent indentation becomes more
important when control structures are nested. Every clause
needs to be indented form its containing statement and all
indentations should use consistent distances.”
/* postconditon
(s <0 || s > 100) IMPLIES result == ‘X’
AND (60<=s<=100) IMPLIES result ==’P’
AND (0 <=s<=59) IMPLIES result == ‘F’ */
private char gradePassFail( int s )
{
char result
if (s < 0 || s > 100 ) {
System.out.println(“ERROR – invalid test score.”;
result = ‘X’;
} else {
if ( s <= 60 ) {
result = ‘P’;
} else {
result = ‘F’;
}
}
return result;
}
Use of braces
A dangling else code pattern consists of an if-then-else
instruction with an if-then nested as the then clause.
With braces, there is no problem.
if ( condition1 ) {
if (condition2 ) {
thenStatement;
}
} else {
elseStatement;
}
With nonessential braces removed, the code fails to
clearly indicate the end of the then clause from the outer if
instruction.
if ( condition1 )
if (condition2 )
thenStatement;
else
elseStatement;
The Java compiler matches else clauses with the most
recent possiblility. i.e. the else is paired with the inner
if.
7.7 Multiway selection
Selections involving more than two alternatives (multiway
selection) is best done with an “else-if construction”.
This is also known as cascading conditions.
/* postconditon
(c is NOT a valid uppercase letter form the
telephone keypad)IMPLIES an error message is
output and result == -1
(C is a valid uppercase letter from the telephone
keypad)IMPLIES result == the keypad digit
corresponding to c */
private int teleDigit( char c ) {
if (‘A’ <= c && c <= ‘C’ ) {
return 2;
} else if ( ‘D’ <= c && c <= ‘F’ )
return 3;
} else if ( ‘G’ <= c && c <= ‘I’ )
return 4;
} else if ( ‘J’ <= c && c <= ‘L’ )
return 5;
} else if ( ‘M’ <= c && c <= ‘O’ )
return 6;
} else if ( c == ‘P’ || c = ‘R’ ||
return 7;
} else if ( ‘T’ <= c && c <= ‘V’ )
return 8;
} else if ( ‘W’ <= c && c <= ‘Y’ )
return 9;
} else {
System.out.println( “Error – non
character.”);
return -1;
}
}
{
{
{
{
c = ‘S’ ) {
{
{
digit key
7.8 The switch instruction
Differs from the if:
The switch instruction is not restricted to two-way
selection, but supports multiway selection without any
nesting.
The clause selection is base upon the value of an int (or
char) expression rather than a boolean conditon.
switch ( letterGrade ) {
case ‘A’ :
System.out.println(
System.out.println(
break;
case ‘B’ :
System.out.println(
System.out.println(
break;
case ‘C’ :
System.out.println(
System.out.println(
break;
case ‘D’ :
System.out.println(
System.out.println(
break;
case ‘F’ :
System.out.println(
System.out.println(
break;
default :
System.out.println(
break;
}
“Your grade is an A.” );
“Excellent work!” );
“Your grade is an B.” );
“Above average.” );
“Your grade is an C.” );
“Average grade.” );
“Your grade is an D.” );
“Below average” );
“Your grade is an F.” );
“Excellent work!” );
“Invalid grade.” );
Format is
word switch, followed by switch expression in parens
Switch expression must be of type int or char
followed by zero or more case clauses
(the word case followed by a case constant, followed by a
colon and the code of the clause)
Case constants must be constants and not
expressions containing variables
No case constant may appear more than once in a
single switch
Needs a break instruction at the end of a clause.
ended with the default clause
No more than one default clause may be included in a
single switch
Switch works best when there is a natural integer expression
or character for the case.
7.9 Software testing
Software testing – exercise the program to uncover bugs.
Test suite consisting of test cases is used to test the
program under varying conditions.
Black-box testing – testing done without knowledge of
specific code details
Black-box is also known as functional testing – done
without knowledge of implementation
Test using pre and post condtions
robustness – does the program continue to work under
unexpected conditions
White-box testing – testing done with full knowledge of
code details
White-box testing also known as structural testing
Focus on the code structure
Issue is statement coverage, where goal is that each
statement in the program has been covered at least once.
Path coverage measures whether each possible path
through the program has been tested… may be many
7.10 Logic and programming (optional)
“An understanding of the rules of logic is of great benefit to
a programmer.
Using logical axioms and theorems to simplify Boolean
expression is helpful for readability and debugging….
eliminate all unnecessary NOT operators.
7.11 Assertions (optional)
“An assertion is a logical statement that defines the state of a
computation at some location within the code.
makeTriangle();
/* assert
side1 > 0 && side2 > 0 && side3 > 0
&& side1 + side2 > side3 */
Most postconditions are expressed as a collection of
several logical conditions that are all asserted.
/* postcondition
r.getColor() == Color.green
AND r.isFilled() */
/* postcondition
(d1 <= d2 IMPLIES resutlt == d1
AND (d1 > d2) IMPLIES result == d2 */
IMPLIES is not a valid Java Boolean operator,
but an assert method can be included in any class as a
basic tool for assertion checking
Calls to the assert method can be used as a debugging
technique.
/* postcondtion
(NOT b) IMPLIES meg is output */
private void assert(booean b, String msg) {
if (!b ) {
System.out.println( “assert violate” + msg );
}
}
/* precondition
r != null
postcondition
r.getColor() == Color.green
AND r.isFilled() */
private void makeFilledGreen( Arectangle r ) {
assert( r!=null,
“makeFilledGreen called with null arg” );
r.setToFill();
r.setColor( Color.green );
assert( r.getColor() != Color.green || !(r.isFilled()),
“makeFilledGreen violation of postcondition” );
}
From Java.Sun.com:
USING ASSERTIONS
Assertions are a new feature in Java 2 Platform, Standard Edition J2SE version 1.4. An assertion is a
program statement containing a boolean expression, that a programmer believes to be true at the time the
statement is executed. Assertions are used during development as a sort of internal sanity check, and
typically are disabled when an application is deployed. The Java implementation of assertions involves both
a language change (the assert keyword) and support in the library (java.lang.AssertionError).
This tip looks at some of the details around using assertions. It also discusses where you might want to
employ assertions in your Java programs. Let's start with a simple example:
public class AssertDemo1 {
static void f() {
assert false;
}
public static void main(String args[]) {
try {
f();
}
catch (AssertionError e) {
System.out.println("exception: " + e);
}
}
}
If you compile and run this program by saying:
javac -source 1.4 AssertDemo1.java
java -ea AssertDemo1
the result is:
exception: java.lang.AssertionError
The -source option is new for J2SE v 1.4. It's a special compilation switch that is required because
assert is now a keyword rather than an identifier. Programs that use assert as an identifier will break if
assert is assumed to be a keyword. The switch is used as a transition mechanism.
The -ea switch is used to enable assertions at application run time. Without this switch, assert
statements are ignored, but are still present in the bytecodes generated by the compiler.
If assertions are enabled, and the Java interpreter encounters a statement of the form:
assert boolean-expression;
it evaluates the expression. If the expression is false, the Java interpreter throws an AssertionError
exception. Because assertions can be disabled, the expression that's evaluated should be free of side
effects, that is, it should not change any state that is visible after evaluation is complete.
ETC……