Week 3 slides

advertisement
Selection statements
Repetition statements
Lesson plan
• Main concepts
• Practice session
– If- then
– Switch
– Nested if
Sequential sequence and
Control Statement
• Sequential sequences are
insufficient to solve most
problems.
– Get in the Car.
– Drive to the supermarket.
• Tank nearly empty?
– Get in the Car.
– If we need gas, then fill up.
– Drive to the supermarket.
Dependent Actions
• A question is asked.
– A condition is checked.
• The dependent actions are only
performed if the answer is Yes (the
condition is true).
• Sometimes the dependent actions
are performed, and sometimes they
are not.
Example: Logging In
• Computer access:
– Request a login name from the
user.
– Request a matching password.
– If the password matches the
login name, then grant access.
Simple Choice Statement
if (<boolean expression>)
<block>;
else
<block>;
if (<boolean expression>)
single statement;
else
single statement;
Boolean expression
• Boolean expression: is a conditional
expression that is evaluated to either
true or false.
• Conditional expression: is a three part
expression:
<exp.>
<relational operators>
<exp.>
• Boolean expressions can be combined
by boolean operators
Relational Operators
a
a
a
a
a
a
Expression
== b
!= b
> b
< b
>= b
<= b
Meaning
Is a equal to b?
Is a not equal to b?
Is a greater than b?
Is a less than b?
Is a greater than or equal to b?
Is a less than or equal to b?
Boolean operators
&&
||
!
means
means
means
AND
OR
NOT
Boolean Operators
Operator a
b
&&
false
any-value false
&&
true
false
false
&&
true
true
true
||
true
any-value true
||
false
false
false
||
false
true
true
Result
Example of Boolean expression
testScore < 62
age > 35
Height > 6.5
(testScore < 62) && (age > 35)
testScore = 95 ???????
Block
- Represents compound statement
{
<statement 1>
<statement 2>
<statement 3>
}
Example
If (age < 35) {
coPay = 5;
System.out.println(“….”);
}
Else {
coPay = 10;
System.out.println(“….”);
}
Practice
• Identify invalid boolean
expression
• Identify invalid If-then-else
statement
Answers for last practice exercise
I.
(i) (x+1>=0) && (x==1)
Valid
(ii) x2+2x-1
Invalid. Arithmetic expression
(iii) ((y%2) != 0)
Valid
Answers to last practice exercise
if (x==y) {
System.out.println(“ x=y”);
}
Else {
System.out.println(“ x does not
equal to y”);
}
Should be
Lowercase
Answers to last practice exercise
if (x=y) then {
grade = “A”;
}
else {
Grade = “B”;
}
If we actually ask (is
x equal y) then it
should be (x==y)
Answers to last practice exercise
if (x==y) {
grade = “A”;
else
grade = “B”;
}
Hanging “else”
Simple Choice Statement
if (<boolean expression>)
<block>;
[else
<block>;] // optional
if (<boolean expression>)
single statement;
[else
single statement;] // optional
Answers to some questions
• Java machine code is generated
and stored in *.class files. For
example:
– LoanCalculator.java
– LoanCalculator.class
• When we compile a java program
outside of Textpad, we need to
use:
javac.exe <source_name>
• When we run a java program
outside of Textpad, we need to
use:
java.exe <class_name>
Answers to some questions
• How to clear screen from DOS:
for (int i=0; i<25; i++)
System.out.println();
Nested If Statement
if (<boolean expression>)
if (<boolean expression>)
if (<boolean expression>) {
statement 1
}
else if (<boolean expression>) {
statement 2
}
else {
statement 3
}
else ….
Example
if (score >= 95)
grade= “A”;
else if (score >=90)
grade=“A-”;
else if (score>=85)
grade =“B+”;
SWITCH statement
switch (variable) {
<case label 1>: <case body 1>
……
<case label 2>: <case body 2>
}
<case label i>: has the form
case <constant>
or: default
<case body i>: is a block or a single statement,
with break
variable: of integer, or char data type
Example
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
……………..
default: System.out.println("Not a month!");
break;
}
Char data type & boolean data type
• Char:
– It is 2 bytes
– Char constant is denoted by single
quote:
for example: ‘s’, ‘h’
Special characters:
\b backspace, \t tab
• Boolean:
- Can be true or false
Examples
char aLetter;
aLetter =‘k’;
…
aLetter =‘k’;
boolean flag;
flag = true;
…
flag = false;
Practice
Evaluate boolean expressions
Identify invalid Switch statement
Project 1 (d)
• Exit the system normally:
– System.exit(0);
• Exit the system abnormally:
e.g: System.exit(1);
– a nonzero status code indicates
abnormal termination.
Repetition statements
• Repetition of statements is a further
common facet of everyday life and
object behavior:
– Repeat every day:
• Get up; have breakfast; go off to work; have
lunch; do more work; have an evening meal;
relax; go to bed.
• Java has three types of loop for
repetition:
– while, do-while, for.
The While Loop
while(<boolean expression>){
// Repeat multiple statements.
statement 1
statement 2
statement 3
...
}
Example
// Print the numbers 1 to maximum.
Assuming that maximum is 100
int maximum = 100;
int nextToPrint = 1;
while(nextToPrint <= maximum){
System.out.print(nextToPrint+" ");
// Get ready to print the next number.
nextToPrint = nextToPrint +1;
}
System.out.println();
}
The Do Loop
do{
// Repeat multiple statements.
statement 1
statement 2
statement 3
...
} while(<boolean expression);
•Note that the statements in the body of the loop
are always executed at least one.
•Note the final semicolon, which is required.
Printing a Sequence
int maximum = 100;
int nextToPrint = 1;
do{
System.out.print(nextToPrint+" ");
// Get ready for the next number.
nextToPrint = nextToPrint + 1;
}
while(nextToPrint <= maximum);
System.out.println();
}
The For Loop
• Used to repeat statements a fixed
number of times:
– Add three teaspoons of sugar.
– Knock twice and then give the
password.
• Used very often with arrays and
collections of objects
• Similar in effect to the while loop.
The For-Loop Outline
// Repeat multiple statements.
for(initialization; condition; post-body update){
// Statements to be repeated.
statement 1
statement 2
statement 3
...
}
•Commonly used with increment
and decrement operators.
Increment and Decrement
• Used as a shorthand for add-one-to
and subtract-one-from:
• value = value+1;
• value += 1;
• value++;
• Prefix and postfix forms:
• ++value;
• --value;
• value--;
A For Loop to Print a Sequence
int maximum = 100;
int nextToPrint;
for(nextToPrint = 1; nextToPrint <= maximum;
nextToPrint++){
System.out.print(nextToPrint+“$“+” ”);
}
System.out.println();
The variable is not available outside the loop
1234567891011
1$ 2$ 3$ 4$ 5$ 6$.
Practice
Develop a java class called:
SumCalculator.java
which computes a sum of all integer
from 1 to 100 and displays the
result to the screen
Download