Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
11
Logical Operators  
and switch
Stuart Gibson
sg@sys.uea.ac.uk
S01.09A 
Lecture 5
SYS-1S22 / MTH-1A66
2
Relational and Equivalence Operators
Relational 
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Equivalence
Operator Meaning
== equal to
!= not equal to
• A variable may be tested against a constant 
or another variable.
3
Examples of Simple Logical Expressions
final int b=21;
final char no = ‘n’;
int a = 20;
int c = 20;
char choice = ‘y’;
Expression Value
a < b true
a == c true
c > b false
choice == no false
c != a false (Incorrect in Lecture 4 L)
• In the last lecture we saw how these logical expressions are 
evaluated at run time as either true or false.
4
Evaluation of logical expressions
int a=10, b=20, c=5;
if( a < b )
{
if ( a > c )
{
System.out.println(“Second if”);
}
System.out.println(“End of first if”);
}
else
{
System.out.println(“In else”);
}
System.out.println(“After”);
10 < 20
evaluates to true
evaluates to
10 > 5
evaluates to
true
evaluates to
Flow of program 
execution.
Second if
End of first if
After
Output
25
Evaluation of logical expressions
int a=10, b=20, c=25;
if( a < b )
{
if ( a > c )
{
System.out.println(“Second if”);
}
System.out.println(“End of first if”);
}
else
{
System.out.println(“In else”);
}
System.out.println(“After”);
10 < 20
evaluates to true
evaluates to
10 > 25
evaluates to
false
evaluates to
Flow of program 
execution.End of first ifAfter
Output
6
Evaluation of logical expressions
int a=25, b=20, c=25;
if( a < b )
{
if ( a > c )
{
System.out.println(“Second if”);
}
System.out.println(“End of first if”);
}
else
{
System.out.println(“In else”);
}
System.out.println(“After”);
25 < 20
evaluates to false
evaluates to
Flow of program 
execution.In elseAfter
Output
Does NOT get 
evaluated 
as the first if 
statement 
evaluates to 
false.
7
Logical Operators
• The logical operators AND, OR and NOT can be used 
in Java to form more complex logical expressions by 
combining simple logical expressions.
One ArgumentNOT!
Two ArgumentsOR||
Two ArgumentsAND&&
8
The AND Operator ( && )
• Example:
if ( x >= 0 && x <= 10)
System.out.print(“x in range 0 to 10”);
• An AND expression evaluates as true only if BOTH 
arguments are true. 
• Truth Table:
falsefalsefalse
falsetruefalse
falsefalsetrue
truetruetrue
Argument 1 && Argument 2Argument 2Argument 1
39
The AND Operator ( && ) - Examples
int x = 10, y = 11, z = -3;
if (x > z && x > y)
è(10 > -3 && 10 > 11)
è(true && false)
è false
if (z < x && y > x)
è(-3 < 10 && 11 > 10)
è(true && true)
è true
if (z > x && x > y)
è(-3 > 10 && 10 > 11)
è(false && false)
è false
10
The OR Operator ( || )
• Example:
if ( x < 0 || x > 100)
System.out.print(“x is invalid”);
• An OR expression evaluates as true if EITHER arguments 
are evaluated as true. 
• Truth Table:
falsefalsefalse
truetruefalse
truefalsetrue
truetruetrue
Argument 1 || Argument 2Argument 2Argument 1
11
The OR Operator ( || ) - Examples
int x = 10, y = 11, z = -3;
if( x > z || x > y )
è(10 > -3 || 10 > 11)
è(true || false)
è true
if( z < x || y > x )
è(-3 < 10 || 11 > 10)
è(true || true)
è true
if( z > x || x > y )
è(-3 > 10 || 10 > 11)
è(false || false)
è false
12
Evaluation of  && and || Operator
• The computer is quite clever, so when evaluating && and ||
operators in some cases it only evaluates the first argument.
For example:
int a = 0;
if (a > 0 && b / a > 1)
• In an AND (&&) statement, if the first argument is false, then 
whatever the second argument is, doesn’t matter! This is 
because according to the truth table, any combination starting 
with false evaluates to false.
• In an OR (||) statement, if the first argument evaluates to 
true, then whatever the second argument is, doesn’t matter! 
This is because and combination starting with true, evaluates 
to true.
413
The NOT Operator ( ! )
• Example:
if ( ! ( x == y ) )
{
System.out.print(“x is not equal to y”);
System.out.print(“easier to use x!=y in”);
System.out.print(“ this case.”);
}
• A NOT expression is true when its argument is false.
• Truth Table:
falsetrue
truefalse
! ArgumentArgument
14
The NOT Operator ( ! ) - Examples
int x = 10, y = 11, z = -3;
if( !( x > z ))
è!(10 > -3)
è!(true)
è false
if( !( z > y ))
è!(-3 > 11)
è!(false)
è true
15
Compound Logical Expressions
• We can build more complex expressions containing more 
than one logical operator.
int x = 1, y = 2, z =3;
x == 1 || y == 2 && z == 4
• Unless parentheses (brackets) are used AND is always 
evaluated before OR so:
x == 1 || y == 2 && z == 4
x == 1 || true && false
x == 1 || false
true || false
true
But we could rewrite it using parentheses as: 16
Compound Logical Expressions
int x = 1, y = 2, z =3;
( x == 1 || y == 2 ) && z == 4
• Now the expression in the parentheses is evaluated first: 
( x == 1 || y == 2 ) && z == 4
( true || true ) && z == 4
true && z == 4
true && false
false
• However the expression to evaluate can be even more 
complicated such as:
if ( !( x > y && y < z) && z > 0 || (y>=12))
517
Compound Logical Expressions
if ( !( x > y && y < z) && z > 0 || (y>=12))
• Q: How does the computer know what to evaluate first ?
A: Precedence !
• Brackets have the highest precedence. Always solve the 
deepest nested set first (L:N where N is the level of nesting):
if ((x >5 && (y < z || y > 3)) && (a > 3))
L:1
L:2
L:3 L:3
L:2 L:2 L:2
L:1
• So, solve level 3 (deepest nested) first, then level2, note ties 
on the same level are solved left to right and finally level 1. 18
Precedence Table
Assignment=
Logical OR||
Logical AND&&
Equivalence operators==  !=
Relational operators<  <=  >=  >
Addition and subtraction+  -
Multiplication, division and mod*  /  % 
Logical not, unary plus and minus!  +  -
DescriptionOperator Highest
Lowest
19
More Logical Expressions
• Logical expression can involve arithmetic operators:
if ((x = y + 5) > 10 && (z = z + y) == 4))
System.out.print(“Some condition met”);
• But it is much better to write:
x = y + 5;
z = z + y;
if (x > 10 && z == 4)
System.out.print(“Some condition met”)
20
Character Comparisons
• You can compare characters as well:
Expression Value
‘A’ < ‘B’ true
‘A’ < ‘a’ true
‘?’ > ‘@’ false
• Q: Where does those values come from ?
A: The computer converts the characters to numbers and then 
compares those numbers.
• The numbers come from the ASCII / UNICODE values:
A = 65,  B = 66,  a =  97, ? = 63, @ = 64.
621
Control Structures
• In the last lecture we saw that there were three main types of 
Control Structures:
• Sequence
• Selection
• Repetition
• Selection
So far we have seen the following Java control sequences:
One Alternative: if statement
Two Alternatives: if else statement
More than two Alternatives: nested if else statements
22
Selection: switch
• switch statements can be used to chose between one of 
several alternatives.
• The alternatives are dependant on the value of a selector
• The selector must be an expression that evaluates to an 
integer (int), character (char), or boolean. 
• Note that with boolean selector you can only have two 
choices, true or false, like a two alternative, if else
statement.
23
switch statement
switch( selector )
{
case label1:
statements1;
break;
case label2:
statements2;
break;
.
.
case labeln:
statementsn;
break;
default:
statementsd;
} 24
switch statement
• switch statements provide an alternative syntax to multiple 
if statements. Consider the following nested if:
char staffType;
… … …
if( staffType == ‘A’)
System.out.print(“Academic Staff”);
else if( staffType == ‘U’ )
System.out.print(“Undergraduate Student”);
else if( staffType == ‘P’ )
System.out.print(“Postgraduate Student”);
else if( staffType == ‘T’ )
System.out.print(“Technical Staff”);
else
System.out.print(“Unknown Staff Type”);
725
switch statement
char staffType;
… … …
switch (staffType)
{
case ‘A’:
System.out.print(“Academic Staff”);
break;
case ‘U’:
System.out.print(“Undergraduate Student”);
break;
case ‘P’:
System.out.print(“Postgraduate Student”);
break;
case ‘T’:
System.out.print(“Technical Staff”);
break;
default :
System.out.print(“Unknown Staff Type”);
} 26
Execution of a switch statement
• The selector expression is evaluated and compared to each 
case label in turn, for example:
staffType = ‘P’;
case ‘A’: à staffType == ‘A’ à ‘P’ == ‘A’ à false
case ‘U’: à staffType == ‘U’ à ‘P’ == ‘U’ à false
case ‘P’: à staffType == ‘P’ à ‘P’ == ‘P’ à true
• If the selector is equal to the condition of one of the case 
labels, then the statements associated to this case are 
executed, so in our example the output would be:
Postgraduate Student
27
switch – the use of break
• All statements after the matched case label are executed until 
a break statement is reached.
• The purpose of the break statement is to break out of the 
current control structure, in this case the switch statement.
• In our example where staffType = ‘P’; the program 
executes the one line of code associated with the case ‘P’:
and then breaks out of the switch. Program execution 
continues at the next statement after the last curly brace of the 
switch statement.
28
switch – with break
char staffType;
staffType = ‘P’;
switch (staffType)
{
case ‘A’:
System.out.print(“Academic Staff”);
break;
case ‘U’:
System.out.print(“Undergraduate Student”);
break;
case ‘P’:
System.out.print(“Postgraduate Student”);
break;
case ‘T’:
System.out.print(“Technical Staff”);
break;
default :
System.out.print(“Unknown Staff Type”);
}
System.out.println(“After Switch”);
false
false
true
At the break
execution
jumps to after 
the switch
Postgraduate Student
After Switch
Output
Flow of execution
829
switch – missing break
char staffType;
staffType = ‘P’;
switch (staffType)
{
case ‘A’:
System.out.print(“Academic Staff”);
case ‘U’:
System.out.print(“Undergraduate Student”);
case ‘P’:
System.out.print(“Postgraduate Student”);
case ‘T’:
System.out.print(“Technical Staff”);
default :
System.out.print(“Unknown Staff Type”);
}
System.out.println(“After Switch”);
false
false
true
Without 
break
statements
execution
continues 
through
the switch
Postgraduate Student
Technical Staff
Unknown Staff Type
After Switch
Output
Flow of execution
30
switch – default case
• In our example what would happen if  staffType was Z ?
staffType = ‘Z’;
case ‘A’: à staffType == ‘A’ à ‘P’ == ‘A’ à false
case ‘U’: à staffType == ‘U’ à ‘P’ == ‘U’ à false
case ‘P’: à staffType == ‘P’ à ‘P’ == ‘P’ à false
case ‘T’: à staffType == ‘P’ à ‘P’ == ‘P’ à false
default : à true
• If none of the case labels are matched, the statements 
associated with the default case are executed.
• A default case is optional in a switch statement.
Unknown Staff Type
31
switch – definition errors
• Each case label is a single, constant value and each label 
must be different.
case ‘U’:
System.out.print(“Undergraduate Student”);
break;
case ‘U’:
System.out.print(“Postgraduate Student”);
break;
• Gives the following error:
HelloWorld.java:15: duplicate case label
case 'U':
^
1 error
32
switch with integers (int)
int numWheels;
… … …
switch (numWheels)
{
case 1:
System.out.print(“Unicycle”);
break;
case 2:
System.out.print(“Bike”);
break;
case 3:
System.out.print(“Trike”);
break;
case 4:
System.out.print(“Stabilisers”);
break;
default :
System.out.print(“Weird Bike!”);
}
933
Multiple cases
• You can have multiple cases associated with a single set of statements:
int employeeCode = 3;
switch (employeeCode)
{
case 0: case 1:
salary = salaryLevel_1;
break;
case 2: case 3: case 4:
salary = salaryLevel_2;
break;
case 5:
salary = managerLevel;
break;
default :
System.out.print(“Unknown Employee Code”);
}
• However each case has to be specified individually in a list as you can not 
specify a range of values. 34
Multiple cases – NO range!
• For example trying to specify a range would give you an error:
int employeeCode = 3;
switch (employeeCode)
{
case employeeCode <=1:
…
HelloWorld.java:9: incompatible types
found   : boolean
required: int
case employeeCode <=1:
^
1 error
35
switch – case sensitive
• Remember Java is case sensitive! 
• If your switch selector is a character, you need to deal with 
both upper and lower case letters, for example:
case ‘U’: case ‘u’:
System.out.print(“Undergraduate Student”);
break;
• A more advanced solution would be to convert the selector to 
uppercase or lowercase before entering the switch
statement, more later…