








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Paper; Professor: Gotel; Class: Computer Programming I; Subject: Computer Science; University: Pace University-New York; Term: Unknown 2008;
Typology: Papers
1 / 14
This page cannot be seen from the preview
Don't miss anything!
CS121/IS223 Week 2, Slide 1
Conditionals in Java
Dr Olly Gotel
ogotel@pace.edu
http://csis.pace.edu/~ogotel
Having problems?
-- Come see me or call me in my office hours
-- Use the CSIS programming tutors
CS121/IS223 Week 2, Slide 2
This Week’s Agenda
CS121/IS223 Week 2, Slide 3
Back to Basics
Input Output Do something
Just focusing on keyboard
IP & screen OP
CS121/IS223 Week 2, Slide 4
Scanner
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String name;
int age;
name = scan.nextLine();
age = scan.nextInt();
System.out.println(name + age);
Reminder for input
Pick the method to
read in your type
CS121/IS223 Week 2, Slide 5
From last week
CS121/IS223 Week 2, Slide 6
Writing a Small Program
2 )
3 )
called, who wrote it, when, what it does &
anything else you consider useful)
Practice at home
CS121/IS223 Week 2, Slide 7
Write Another
variable
called, who wrote it, when, what it does &
anything else you consider useful)
Practice at home
CS121/IS223 Week 2, Slide 8
Write Another
variable
will be by the end of 2008
called, who wrote it, when, what it does &
anything else you consider useful)
Practice at home
CS121/IS223 Week 2, Slide 9
Control Structures
statements are executed
statements to regulate flow of control:
choose one set of statements over one or more
other sets
until a stopping condition is reached
The theme for two weeks
CS121/IS223 Week 2, Slide 10
Control Structures
Conditionals enable
selection/choice
Loops enable
repetition
CS121/IS223 Week 2, Slide 11
To Understand Conditionals…
If desired, serve with Maple Mustard Sauce
CS121/IS223 Week 2, Slide 12
Why? Let’s Play a Game to See
“You are standing on the balcony of a castle turret. There is a
cannon & a match. To the north you see a hoard of fire demons
approaching. The rail on the east side of the balcony is broken.”
What do you do?
Hamish McTavish & the Haggis on the Moors
After a few more
classes, you could
write a program
to play this game!
CS121/IS223 Week 2, Slide 19
Being Choosy
value of an expression:
“to be or not to be”
CS121/IS223 Week 2, Slide 20
Booleans
Java has a type
called boolean
Qubit?
CS121/IS223 Week 2, Slide 21
What is the Boolean Value of…
This class is a programming class
Pace University is in New York
New York is the capital of New York
There are 20 days until Olly’s birthday
It is raining today
The student next to you has $10 in their pocket
The Brooklyn Bridge is in Queens
Leeds Castle is in Leeds, UK
$1 has the same value as 100 cents
There are 5 cm in 1 inch
Don’t necessarily evaluate to the same truth value!
CS121/IS223 Week 2, Slide 22
Comparison Operators
There are still more
operators to meet…
Also called
relational
operators
Higher precedence
Lower precedence
They help us to
form boolean
expressions
CS121/IS223 Week 2, Slide 23
VERY IMPORTANT!!!
== is the equivalence operator:
= is the assignment operator:
of y
These are VERY DIFFERENT
get used to this!
CS121/IS223 Week 2, Slide 24
Comparison Operators Return Booleans
characters (see http://www.unicode.org/ ) - BUT YOU CANNOT USE ==
IN JAVA!!!! Remember this for later!
Boolean values
See slide 132 from week 1
CS121/IS223 Week 2, Slide 25
What is the Boolean Value of…
“apples” == “oranges”
type (6.2) != type (6)
“first” < “second”
We cannot compare
strings this way in
Java - try and see
what happens!
CS121/IS223 Week 2, Slide 26
Conditionals
through a program
condition is true, otherwise the
program ignores it
otherwise don’t bother
raining” is true
When may you want to use conditionals?
CS121/IS223 Week 2, Slide 27
Why Use Conditionals?
We also test conditions when we check
whether we should do something again
CS121/IS223 Week 2, Slide 28
Conditionals in Java
conditions
CS121/IS223 Week 2, Slide 29
if-else statements
some interest, but if it is in debit you pay an
overdrawn charge:
if (balance >= 0)
balance = balance + (RATE * balance);
else
balance = balance – penalty;
boolean expression to check – true or false?
MUST have the brackets
Executed if expression is true
Executed if expression is false
The else part
is optional
if statements are found
in MANY languages
Reserved words
CS121/IS223 Week 2, Slide 30
Flowchart of Logic
balance >= 0?
balance = balance
balance = balance
CS121/IS223 Week 2, Slide 37
Case Sensitive?
myString.equalsIgnoreCase(anotherString)
Any guesses?
CS121/IS223 Week 2, Slide 38
Write Some if Statements To…
a) Print an error message if the input value is zero
b) Print a greeting if the input value is your name
c) Print a message if the input value is a negative
number
d) Print a message if the input value is greater than an
allowed number
e) Print an error message if the input value is not “Fire
Cannon!”
Practice at home
CS121/IS223 Week 2, Slide 39
Extend the Previous Examples…
statement examples, to (in turn):
a) Print the input value
b) Print a “Hello stranger!” message
c) Print a message that says the number is not negative
d) Print a message that says the input value is valid
e) Print “Firing Cannon Now!”
Practice at home
CS121/IS223 Week 2, Slide 40
Conditionals: The Rules
value (i.e. true or false value)
statement
statement
optional)
CS121/IS223 Week 2, Slide 41
Turning the Game Flowchart into Java
Prompt user for command
Is command “Go”?
Is command “Take”?
Is command “Strike
match”?
Print “Go”
Print “Take”
Print “Strike match”
Print “Fire cannon”
Call your file
Game.java
Yes
Yes
Yes
No
No
No
CS121/IS223 Week 2, Slide 42
PROJECT 1!!!
in the week…so get thinking!
Download separate
handout on my website
CS121/IS223 Week 2, Slide 43
Game Design Process
you’ll get really bored
writing it, & think of the
poor users!
creative!
02/17/09– note, this is not
the code – this is your game
idea and logic (your
responsibility to show me if
you want guidance)
© According to http://www.looneylabs.com/ CS121/IS223 Week 2, Slide 44
Where Does the else Belong?
if ( a < 0)
if ( b < 0)
b = b + 1;
else
a = a + 1;
if ( a < 0)
if ( b < 0)
b = b + 1;
else
a = a + 1;
Use braces or you will get confused !!!
CS121/IS223 Week 2, Slide 45
Compound if-else Statements
if (balance >= 0){
balance = balance + (RATE * balance);
System.out.println(“In credit”);
else{
balance = balance – penalty;
System.out.println(“In debt”);
Braces enclose a sequence of
statements to execute
A compound statement is a list
of statements within braces
Also called a block statement
CS121/IS223 Week 2, Slide 46
General Structure of if-else Statements
if (condition1){
statement 1;
else if (condition2){
statement 2;
else
default statement X;
Boolean expression
These parts of the if
statement are optional
statement with no
else ; you can have an
if – else if
statement with no
else , etc
Only 1 if; only 1 else; multiple else if
CS121/IS223 Week 2, Slide 47
Booleans
are equal:
values:
Lower precedence than
arithmetic operators
Think: can we use these with doubles?
CS121/IS223 Week 2, Slide 48
Booleans – A Simplification
used in test situations
boolean isPositive = (number >= 0);
boolean isNegative = (number < 0);
boolean okTemp = ((temp > 0) && (temp < 100));
if (okTemp)
doSomething;
Used sensibly, can be easier to read
(boolean variable)
CS121/IS223 Week 2, Slide 55
An Aside - A Bit of Terminology
value) is often called a flag
isHot
keepPlaying
gameOver
gotMoney
if (gotMilk):
print “I’m drinking it…”
CS121/IS223 Week 2, Slide 56
Boolean (Logical) Operators in Java
if ((time > min) && (time < max))
System.out.println(“Ok to sunbathe”);
else
System.out.println(“Come inside!”);
if ((temp < min) || (temp > max))
System.out.println(“Not healthy”);
else
System.out.println(“Healthy!”);
Produce boolean results
CS121/IS223 Week 2, Slide 57
Boolean Operators Cont…
if (!complete)
System.out.println(“Finish up”);
else
System.out.println(“Well done!”);
Logical complement
CS121/IS223 Week 2, Slide 58
Using Boolean Variables in Java
boolean ok = ((time > min) && (time < max));
if (ok)
System.out.println(“Ok to sunbathe”);
else
System.out.println(“Come inside!”);
Use if you like this
(boolean variable)
CS121/IS223 Week 2, Slide 59
Multi-Branch if-else Statements
if (balance > 0)
System.out.println(“In credit”);
else if (balance < 0)
System.out.println(“In debt”);
else if (balance == 0)
System.out.println(“No money”);
if (balance > 0)
System.out.println(“In credit”);
else if (balance < 0)
System.out.println(“In debt”);
else
System.out.println(“No money”);
Better
practice to
provide a
default too
What if you’ve
missed all
options?
CS121/IS223 Week 2, Slide 60
Exercise
in a student test, according to the following chart:
A = 90 – 100 (inclusive)
B = 80 – 89 (inclusive)
C = 70 – 79 (inclusive)
D = 60 – 69 (inclusive)
E = 50 – 59 (inclusive)
F = 0 – 49 (inclusive)
Call your file Grade.java
Eliminate options – no redundant
comparisons in the checking!
CS121/IS223 Week 2, Slide 61
An Answer
Change your program to
throw out bogus marks
above 100 or below 0
CS121/IS223 Week 2, Slide 62
Nested Conditionals
if (cash >= 0){
if (shopping > cash)
System.out.println (“Return items”);
else
cash = cash – shopping;
else
System.out.println (“Can’t even shop!”);
Braces NOT strictly needed, but add clarity
CS121/IS223 Week 2, Slide 63
Which Do You Prefer?
if (bonusOne ==‘Y‘ && bonusTwo ==‘Y' && bonusThree ==‘Y')
score = score + 12;
if (bonusOne == ‘Y')
if (bonusTwo == ‘Y’)
if (bonusThree == ‘Y')
score = score + 12;
CS121/IS223 Week 2, Slide 64
Exercise
numbers. Use a nested conditional to work out & print
the maximum of the 3 numbers entered:
Call your file MaxOfThree.java
CS121/IS223 Week 2, Slide 65
An Answer
How would you change this to
detect equal max values?
CS121/IS223 Week 2, Slide 66
Conditional (Ternary) Operator
-? with : provide a short cut for if-else statements
if (x > y)
max = x;
else
max = y
(x > y)? x : y
Can be hard to
read, so avoid!
CS121/IS223 Week 2, Slide 73
switch Statement in Java
way to branch based on the value of an integer or character expression
switch (value){
case ‘g’:
case ‘G’:
film = “the good”;
break;
case ‘b’:
case ‘B”: film = “the bad”;
break;
case ‘u’:
case ‘U’:
film = “the ugly”;
break;
default:
film = “the good, the bad & the ugly”; break;
}
Often used with switch
Sometimes, a
better way of
writing nested ifs
value must be
int or char type
CS121/IS223 Week 2, Slide 74
Example
switch (numberOfQuarts){
case 1:
System.out.println(“25 cents”);
break;
case 2:
System.out.println(“50 cents”);
break;
case 3:
System.out.println(“75 cents”);
break;
case 4:
System.out.println(“1 dollar”);
break;
default:
System.out.println(“Lots of money”);
break;
}
Controlling expression
(in brackets)
Case label
break statement
Optional, but good practice
The break statement –
allows you to exit a
conditional or a loop
CS121/IS223 Week 2, Slide 75
General Structure of switch Statements
switch (controllingExpression){
case caseLabel:
Statement;
break;
case caseLabel:
Statement;
break;
…
default:
Statement;
break;
}
Controlling expression
must evaluate to integer
type (byte, short, int, long)
or char type
Each case label must be a constant of
same type as controllingExpression
Each case must have a
different case label
CS121/IS223 Week 2, Slide 76
Exercise
want to fly (1, 2 or 3), then prints out the cost of an
airline ticket for that class of travel (NYC-LHR) – use a
switch statement & suitable cases – think about it:
a character using the Scanner class? Do some
research!
Call your file Flights.java
CS121/IS223 Week 2, Slide 77
Key Points
depend on different test conditions)
one test condition)
truth value of boolean expressions (you need to know your
operators)
BUT performance suffers if messy!
CS121/IS223 Week 2, Slide 78
Coming Up Next
CS121/IS223 Week 2, Slide 79
Before Next Time…
th or 5th or 6th edition – read Chapter 5.1-5.4 of the Java
book
things that confuse you
answers to the self-review questions
tests … and there may be one coming up soon!
these slides or you will fall behind … come see me or the tutors
if stuck!
Java project… check the website for details