Conditional Statements and Control Structures in Java

Making Choices
The “if” Control
The “else” Control
Boolean Variables
Overview
Having the program choose an action
the if control
comparing Strings
the else control
nesting controls
combining boolean conditions
boolean variables
remembering true/false values
Making a Choice
Calculating an employee’s pay
get their hourly pay
get how many hours they worked
calculate their standard pay
if they worked more than 40 hours:
add overtime pay
issue a cheque for the total pay
Sometimes overtime pay is added;
sometimes it’s not.
Depends on how many hours they worked.
 
Conditional Commands
“Add overtime pay” is 
conditional
computer doesn’t always do that
“worked more than 40 hours” is the 
condition
it’s either 
true
 or 
false
if it’s 
true
, then computer adds overtime pay
if it’s 
false
, the computer 
doesn’t
 add overtime pay
In English/pseudocode:
“if 
they worked more than 40 hours
,
  then 
add overtime pay
The “if” Control
Java syntax:
    
if (
condition
) {
    
conditionalAction
;
}
note braces
go around the command you 
maybe
 want to do
note 
indentation
:
conditional action indented another four spaces!
also note:  no semi-colon on the “if” line
“if they worked over 40 hours” is 
not
 a command
if (hours > 40) {
    pay = pay + …
}
Remember the 
Format
 command in NetBeans!
It will do the indentation for you.
“if” Control Example
System.out.print("Hours this week: ");
hours = kbd.nextDouble();
kbd.nextLine();
pay = rate * hours;
if (hours > 40) {
 
System.out.println("You get overtime pay.");
    pay = pay + rate * 0.5 * (hours – 40);
}
Hours this week: 
30
Hours this week: 
45
You get overtime pay.
no overtime pay
overtime pay
Condition
Conditional Actions
Simple Comparisons
if (hours > 40) 
 “if hours is greater than 40ˮ
Can also put “ifˮ in front of these:
a == b
 
“a is equal to bˮ
a != b
 
“a is not equal to bˮ
a < b
 
“a is less than bˮ
a <= b
 
“a is less than or equal to bˮ
a > b
 
“a is greater than bˮ
a >= b
 
“a is greater than or equal to bˮ
You can’t use the ≤ or ≥ signs in Java.
It doesn’t understand them!
Important Difference
Check
 
whether
 a is equal to b: 
a 
==
 b
two equals signs
Make
 a equal to b: 
a 
=
 b
one equals sign
Do not get them confused
hours == kbd.nextDouble();
if (hours = 40.0) {
Exercises
Write if statements:
if grade is greater than or equal to 50, print out
“You passed!”
if age is less than 18, print out “I’m sorry, but
you’re not allowed to see this movie.”
if guess is equal to secretNumber, print out “You
guessed it!”
if y plus 9 is less than or equal to x times 2, set z
equal to zero.
Sequential “if” Controls
Each “if” is separate
if (midtermGrade < 50) 
{
     System.out.println(
"
You failed the midterm!
 "
);
}
if (finalGrade < 50) 
{
     System.out.println(
"
You failed the final!
 "
);
}
You failed the midterm!
You failed the final!
one
other
neither
You failed the midterm!
You failed the final!
both
Sequential “if” Controls
Each “if” is separate
if (grade < 50) 
{
 
 System.out.println("I’m sorry.  You failed.");
}
if (grade > 90) 
{
 
 System.out.println("That is an excellent grade!");
}
What grade did you get? 
41
I’m sorry.  You failed.
What grade did you get? 
95
That is an excellent grade!
What grade did you get? 
75
one
other
neither
Sequential “if” Controls
Each “if” is separate
if (grade >= 50) 
{
 
 System.out.println("You passed.");
}
if (grade < 80) 
{
 
 System.out.println("You didn’t get an A.");
}
What grade did you get? 
41
You didn’t get an A.
What grade did you get? 
95
You passed.
What grade did you get? 
75
You passed.
You didn’t get an A.
one
other
both
Exercise
What is the output of the following code?
int age = 24;
int height = 180;
int weight = 70;
int income = 120000;
if (age < 18)  {
 
System.out.println(
"
Young!");  }
if (height > 180) { 
 
System.out.println(
"
Tall!");  }
if (weight <= 50)  {
 
System.out.println(
"
Thin!");  }
if (income >= 100000) { 
 
System.out.println(
"
Rich!");  }
Making a Choice
Taking a lunch order at Greesieberger’s
ask what sandwich they want
add that sandwich to the order
ask if they want fries with that
if they say yes:
add fries to the order
ask what drink they want
add that drink to the order
Sometimes fries are added to the order;
sometimes they’re not.
Depends on what the user wants.
 
Choosing Fries
Ask the user: Do you want fries with that?
Get user’s answer (should be yes or no)
if the answer was yes, add fries to the order
In Java (but not right)
System.out.print("Do you want fries? ");
String answer = kbd.next();
kbd.nextLine();
if (
"yes" == answer
)
 
Object Variables
Strings are objects
== means “Are they the very same object?” as
in “My car and my wife’s car are the same car”
want “Are they the same value?” as in “I have
the same car as my neighbour”
My Car
My Wife’s Car
My Neighbour’s Car
The String in the  code
What the user typed in
"yes"
"yes"
Objects and Primitives
Strings are objects
String name = "Mark";
Scanners are objects, too
Scanner kbd = new Scanner(System.in);
Data type name starts with a Capital Letter
String, Scanner, Car, Color, …
NOTE: the 
variable name 
starts with a small letter
name, kbd, …
Data types without capitals are 
primitives
int, double, …
Talking to Objects
You can talk to an object:
“Hey, kbd, give me the next int.”
kbd.nextInt();
“Hey, kbd, give me the next line.”
kbd.nextLine();
object name, dot, request name, parentheses
Also known as 
calling a method
nextInt and nextLine are methods
each 
returns
 a value that your program can use
Comparing Strings
Ask one String about the other String
don’t use ==, !=, <, <=, >, >=
they don’t work (or they do the wrong thing)
 
==
 
 
oneString
.equals(
anotherString
)
 
!=
 
 
! 
oneString
.equals(
anotherString
)
 
<
 
 
oneString
.compareTo(
anotherString
)
 < 0
 
<=
 
 
oneString
.compareTo(
anotherString
)
 <= 0
 
>
 
 
oneString
.compareTo(
anotherString
)
 > 0
 
>=
 
 
oneString
.compareTo(
anotherString
)
 >= 0
We won’t use compareTo very often in CSCI 1226.
String Equality
Strings are equal if 
exactly
 the same
"First String".equals("First String")
Any other strings are different!
"First String".equals("Second String")
"First String".equals("first string")
"First String".equals("FirstString")
"First String".equals("First String ")
Exercise:
In each of the false conditions above, what’s
different between the Strings?
 
 
true
false
false
false
false
Choosing Fries
In Java
System.out.println("Do you want fries? ");
String answer = kbd.next();
kbd.nextLine();
if (
"yes".equals(answer)
)
 
only accepts “yes”
does not accept “Yes”, “YES”, …
NOTE:  We could have asked answer if it was equals to “yes”:
answer.equals("yes")
We’d get the same answer.
String.
equalsIgnoreCase
Sometimes don’t care if capital or small
"First String".equalsIgnoreCase("First String")
"First String".equalsIgnoreCase("first string")
Any other strings are different!
"First String".equalsIgnoreCase("Second String")
"First String".equalsIgnoreCase("FirstString")
"First String".equalsIgnoreCase("First String ")
true
false
false
false
true
Choosing Fries
In Java
System.out.println("Do you want fries?");
String answer = kbd.next();
kbd.nextLine();
if (
"yes".equalsIgnoreCase(answer)
)
 
accepts “yes”, “Yes”, “YES”, …
(does not accept “yeah”)
Again, we could have asked answer about “yes”:
answer.equalsIgnoreCase("yes")
We’d get the same answer.
String.
startsWith
Accept any answer starting with “y” as yes
System.out.println("Do you want fries?");
String answer = kbd.next();
kbd.nextLine();
if (
answer.startsWith("y")
)
 
Accepts “yes”, “yeah”, “yup”, but not “Yes”
sadly, there is no “startsWithIgnoreCase” method
There’s also an 
endsWith
 method.
And 
lots
 of others!  Google 
java string
.
String
.toUpperCase/toLowerCase
Ask a string for upper/lower case version
System.out.println("Do you want fries?");
String answer = kbd.next();
kbd.nextLine();
String upperAnswer = answer.toUpperCase();
if (
upperAnswer.
startsWith("Y"))
 
now accepts “Yes”, “yes”, “Yeah, “yup”, …
upperAnswer
 is “YES”, “YES”, “YEAH”, “YUP”
answer
 is still “Yes”, “yes”, “Yeah”, “yup”
String.oneThing
().
another
()
Can combine two steps into one
and more, if you want
System.out.println("Do you want fries?");
String answer = kbd.next();
kbd.nextLine();
if (
answer.toUpperCase().startsWith("Y")
)
 
if answer is “yes”, then answer.toUpperCase() is
“YES”, and 
that
 does start with a “Y”
This works because answer.toUpperCase() is another String.
We can ask 
any
 String a question, even if we haven’t given it a name.
Scanner.oneThing
().
another
()
Can save the String in upper case to start with
and more, if you want
System.out.println("Do you want fries?");
String answer = 
kbd.next().toUpperCase()
;
kbd.nextLine();
if (
answer.startsWith("Y")
)
 
change user’s answer to upper case 
before
 saving it
user enters “yes”; answer is “YES”
user enters “Yup”; answer is “YUP”
This works because kbd.nextLine() is another String.
We asked kbd to give us the next line, and it gives us back a String.
Exercise
Right now we accept anything that starts with
the letter Y (capital or small)
if (answer.toUpperCase().startsWith("Y"))
accepts “You need to speak louder” as “Yes”
it starts with the letter Y
Change the code so that it only accepts
abbreviations of “YES” as “Yes”.
but still allow capital letters
Y, y, YE, ye, YES, yes, Ye, yE, YeS, Yes, …
HINT: we still need to use startsWith and toUpperCase.
But who do we ask, and what do we ask about? 
The “if-else” Control
Do 
exactly one of two 
things
if (
grade < 50
) {
 
 System.out.println(
"
You cannot continue to 1227.
 "
);
}
 
else {
 
 System.out.println(
"
You can continue to 1227!
 "
);
}
note the indentation
What grade did you get? 
41
You cannot continue to 1227.
What grade did you get? 
95
You can continue to 1227!
one
other
The “if-else” Control
Java syntax:
if (
condition
) {
   
 
ifSoAction
;
} else {
    
otherwiseAction
;
}
Does 
exactly
 one of
those two things
two-way choice
 
do this or do that
“if” is one-way
choice
 
do this or not
Better Than Two if Controls
Could rewrite if-else into two if controls:
if (
grade < 50
) {
 
 System.out.println(
"
You cannot continue to 1227.
 "
);
}
if
 
(
grade >= 50
) {
 
 System.out.println(
"
You can continue to 1227!
 "
);
}
but that’s 
error-prone
makes it more likely you’ll make a mistake
Error-Prone Version
What’s wrong with this:
if (
grade < 50
) {
 
 System.out.println(
"
You cannot continue to 1227.
 "
);
}
if
 
(
grade > 50
) {
 
 System.out.println(
"
You can continue to 1227!
 "
);
}
Error-Prone Version
For 1228 you need a 60, so…
copy the code, change 1227 to 1228, and 50 to 60
if (
grade < 
60) {
 
 System.out.println(
"
You cannot continue to 
1228
.
 "
);
}
if
 
(
grade >= 50
) {
 
 System.out.println(
"
You can continue to 
1228
!
 "
);
}
what went wrong?
Binary Choices
Else is for 
either-or
 situations
either you pass or you fail
no program option for incomplete
either you can proceed or you cannot
either go left or go right
no program option for straight
State the condition once
Split options between if-body and else-body
Exercise
Write if-else controls for
if temp is over 30, print “Go swimming”;
otherwise print “Play video games”
if count is zero, print sum divided by count;
otherwise print “No numbers entered”.
if answer starts with a y (or Y), then set price to
$10; otherwise set it to $15.
if num is even, set it equal to n divided by 2;
otherwise set it to n times 3, plus 1
num is even 
 
num % 2 == 0
“if” or “if-else”?
Look at the possible outcomes:
outcome #1
computer prints A B C D
outcome #2
computer prints A D
code:
 
System.out.print("A ");
if  (
something
) {
 
System.out.print("B ");
 
System.out.print("C ");
}
System.out.print("D ");
Sometimes prints B and C;
Sometimes doesn’t:
(if control)
“if” or “if-else”?
Look at the possible outcomes:
outcome #1
computer prints A B D
outcome #2
computer prints A C D
code:
 
System.out.print("A ");
if  (
something
) {
 
System.out.print("B ");
} else {
 
System.out.print("C ");
}
System.out.print("D ");
Sometimes prints B;
Sometimes prints C:
(if-else control)
Exercise
Possible outcomes:
outcome #1:  A B C E F
outcome #2:  A D E F
What is the code?
Possible outcomes:
outcome #1:  A B C D
outcome #2:  A B
What is the code?
Exercise
Possible outcomes:
outcome #1:  A B C F G
outcome #2:  A D E F G
outcome #3:  A B C F
outcome #4:  A D E F
What is the code?
A Common Mistake
Putting braces around everything after if
if (thisIsTrue) {
    doThis();
    andThat();
else
    thisOther();
}
the 
else
 must be 
after
 the closing brace of the 
if
otherwise can’t find the 
if
 it’s the 
else
 for
if-else inside if-else
What time is it? 
9 pm
Good evening!
What time is it? 
9 am
Good morning!
What time is it? 
3 pm
Good afternoon!
What time is it? 
3 am
Good grief!
Evening: 6pm to 11pm.
Afternoon: 12pm to 5pm.
Morning: 7am to 11am.
12am to 6 am.
pm
am
A
E
M
G
Get the Time
// create variables
Scanner kbd = new Scanner(System.in);
int hour;
String amPM;
// get the time
System.out.println("What time is it?");
hour = kbd.nextInt();
// fix weird clock
if (hour == 12) { hour = 0; }
// NOTE: read next word in lower case
amPM = kbd.next().toLowerCase();
kbd.nextLine();
 
// read the Enter key!
Print the Message
// print the appropriate message
if ( amPM.equals("pm") ) {
    if ( hour < 6 ) {
        System.out.println("Good afternoon!");
    } else {
        System.out.println("Good evening!");
    }
} else {
    if ( hour > 6 ) {
        System.out.println("Good morning!");
    } else {
        System.out.println("Good grief!");
    }
}
A
E
M
G
9 AM Message
// print the appropriate message
if ( amPM.equals("pm") ) {
    if ( hour < 6 ) {
        System.out.println("Good afternoon!");
    } else {
        System.out.println("Good evening!");
    }
} else {
    if ( hour > 6 ) {
        System.out.println("Good morning!");
    } else {
        System.out.println("Good grief!");
    }
}
 
"am".equals("pm")? NO
 
9 > 6? YES
Note Indentation
// print the appropriate message
if ( amPM.equals("pm") ) {
    if ( hour < 6 ) {
        System.out.println("Good afternoon!");
    } else {
        System.out.println("Good evening!");
    }
} else {
    if ( hour > 6 ) {
        System.out.println("Good morning!");
    } else {
        System.out.println("Good grief!");
    }
}
8
12
16
Remember the 
Format
 command!
if inside if
You can put if controls inside if controls
if first condition is true, test second condition
System.out.println("A");
if (condition1) {
    System.out.println("B");
    if (condition2) {
        System.out.println("C");
    }
}
possible output:
A
AB
ABC
pattern:
always A
sometimes B
when B, sometimes C
Eligible for Pension
Who is eligible for a pension
seniors (age is 65+)
disabled people 55+ who live on their own
Only ask question if need to know
ask age
if 65+ 
 eligible
if 55+ and not already eligible
ask if disabled
if disabled
ask if live on own
if live on own 
 eligible
Eligible for Pension
// ask age
System.out.print("How old are you? ");
age = kbd.nextInt();
kbd.nextLine();
eligible = (age >= 65);
// if 55..64, ask if disabled
if (age >= 55 && !eligible) {
    System.out.print("Are you disabled? ");
    answer = kbd.nextLine().toLowerCase();
    
// if disabled, ask if live on own
    
if (answer.startsWith("y")) {
        System.out.print("Do you live on your own? ");
        answer = kbd.nextLine().toLowerCase();
        eligible = answer.startsWith("y");
    }
}
Exercise
Write nested if/if-else to generate:
either "A", "AB", "ABC" or "ABD"
either "A", "ABC" or "AC"
either "A", "ABC", or "D"
Logical Operators
p && q
 
p 
and
 q both true
(0 < n) && (n < 100)
p || q
 
either p 
or
 q (or 
both
) are true
(m > 0) || (n > 0)
!p
 
p is 
not
 true
!answer.equals("yes")
On Translating from English
In English we can leave things unsaid
if x is greater than 0 and less than 100, ...
In Java, we can’t
if (x > 0 && 
< 100
) 
 
computer:  Huh??
Start by saying the whole thing in English
if x is greater than 0 and 
x is 
less than 100, ...
if (x > 0 && x < 100)
 
computer:  OK
Warnings
Use the right operators
==
 
 
not
  
=
&&
 
 
not
  
&
||
 
 
not
  
|
Nothing goes without saying!
a > 0  && a < 10
 
not
  
a > 0 && 
< 10
b == 0 || c == 0
 
not
  
b || 
c == 0
0 < d  && d < 10
 
not
  
0 < d 
< 10
Exercises
Write Boolean expressions for whether…
x is greater than 0 and y is less than 5
x is greater than zero or y is equal to z
answer does not start with N
it’s not the case that x is greater than the product of
y and z
NOTE:  translate 
directly
 to Java
y is greater than x and less than z
x is equal to y but not to z
m or n is greater than 0
Three-Way Choice
Exactly one of three options
either "A", "B", or "C"
if (age < 18) {
 
System.out.print("Child");
}
if (age >= 18 && age < 65) {
 
System.out.print("Adult");
}
if (age >= 65) {
 
System.out.print("Senior");
}
Child
age is 15
Adult
age is 25
Senior
age is 65
Sequential If and If-Else
Be careful mixing if with if-else
else parts go with each if separately
if (age < 18) {
 
System.out.print("Child");
}
if (age >= 18 && age < 65) {
 
System.out.print("Adult");
} else {
 
System.out.print("Senior");
}
What happens when age is 15?
Adult
age is 25
Senior
age is 65
If-Else Inside Else
If-Else inside an Else
only do Adult/Senior choice if Child 
not 
chosen
if (age < 18) {
 
System.out.print("Child");
} else {
    if (age >= 18 && age < 65) {
 
    System.out.print("Adult");
    } else {
 
    System.out.print("Senior");
    }
}
Adult
age is 25
Senior
age is 65
What happens when age is 15?
If-Else Inside Else
So common it has a special style
second 
if
 comes 
right after
 the 
else
 (no braces)
if (age < 18)  {
 
System.out.print("Child");
} else if (age >= 18 && age < 65) {
 
System.out.print("Adult");
} else {
 
System.out.print("Senior");
}
behaves exactly the same as previous slide
Cascading If Statements
Simplified conditions
already 
know
 age >= 18 in part 2
if (age < 18) {
 
System.out.print("Child");
} else if (age < 65) {
 
System.out.print("Adult");
} else {
 
System.out.print("Senior");
}
Adult
age is 25
Senior
age is 65
What happens when age is 15?
Multi-Way Choice
A or B or C or ... or Z
 
if (...) {
 
doA();
} else if (...) {
 
doB();
...
} else {
 
doZ();
}
A or B or ... or Z
or 
none of the above
if (...) {
 
doA();
} else if (...) {
 
doB();
...
} else if (...) {
 
doZ();
}
If we didn’t do any of the others,
then we’ll do Z for sure
If we didn’t do any of the others,
we 
still
 might not do Z
Exercises
Write “Good morning
 if time < 12, “Good
afternoon
 if 12 
 
time < 17, “Good evening
otherwise
Write “Small
 if size is 1, “Medium
 if size is
2, “Large
 if size is 3, “X-Large
 if size is 4,
and “XX-Large
 if size is 5
don’t write anything if size is not 1..5
Boolean Values
Comparison operators evaluate to 
true
 or 
false
20 < 40
 is 
true
; 
40 < 20
 is 
false
NOTE: 
true
 and 
"true" 
are entirely different
just like 
65.0
 and 
"65.0"
true
 and 
false
 are called “Boolean” values
after George Boole, who studied logic
20 < 40
 is called a “Boolean expression”
its value is a Boolean value
 
&&
, 
||
 and 
!
 are called “Boolean operators”
allow us to make bigger Boolean expressions
Boolean Variables
Can save the answer to a comparison
use a boolean variable
boolean workedOvertime = (hours > 40);
you don’t 
need
 parentheses, but it’s easier to read
Can use the saved result as a condition
if (
workedOvertime
) {
 
overtimeHours = hours – 40;
 
regularPay = 40 * rate;
 
overtimePay = overtimeHours * rate * 1.5;
}
Boolean Variable
Answer to a “True or False” question
True or False?
a.
The hours worked is over 40.
workedOvertime = (hoursWorked > 40);
 
b.
The midterm grade is less than 50.
failedMidterm = (midtermGrade < 50);
Complex Expressions
Break complex expressions down
boolean failedMidterm, failedFinal, …;
failedMidterm = (midtermGrade < 50);
failedFinal = (finalGrade < 50);
failedBothTests = failedMidterm && failedFinal;
blewOffLabs = (labGrade < 30);
blewOffAsgns = (asgnGrade < 30);
blewOffWork = blewOffLabs && blewOffAsgns;
if (
failedBothTests || blewOffWork
)
 {
 
System.out.println("Special fail rule!");
 
courseGrade = "F";
}
Remember!
Changing the value of one variable doesn’t
change the value of any other variables!
length = 10;
width = 2;
area = length * width;
 
// area is 10 * 2 = 20
width = 5;
 
// area is 
still
 20 -- NOT 50
Applies to boolean variables, too!
age = 15;
isMinor = (age < 18);
 
// isMinor is true
age = 20;
 
// isMinor is 
still
 true -- NOT false
Exercise
Create a variable named saidYes
Ask user if they are an adult
Set saidYes to true or false
true if they said “Yes” (ignoring case)
false otherwise
Can you do it without using any variables for
what the user typed in?
Questions
Slide Note
Embed
Share

Learn about using if and else control structures, boolean variables, and conditional actions in Java programming. Explore examples of making choices and implementing simple comparisons to manage program flow efficiently.

  • Java Programming
  • Conditional Statements
  • Control Structures
  • Boolean Variables
  • Code Examples

Uploaded on Sep 14, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Making Choices The if Control The else Control Boolean Variables

  2. Overview Having the program choose an action the if control comparing Strings the else control nesting controls combining boolean conditions boolean variables remembering true/false values

  3. Making a Choice Calculating an employee s pay get their hourly pay get how many hours they worked calculate their standard pay if they worked more than 40 hours: add overtime pay issue a cheque for the total pay Sometimes overtime pay is added; sometimes it s not. Depends on how many hours they worked.

  4. Conditional Commands Add overtime pay is conditional computer doesn t always do that worked more than 40 hours is the condition it s either true or false if it s true, then computer adds overtime pay if it s false, the computer doesn t add overtime pay In English/pseudocode: if they worked more than 40 hours, then add overtime pay

  5. The if Control Java syntax: if (condition) { conditionalAction; } note braces go around the command you maybe want to do note indentation: conditional action indented another four spaces! also note: no semi-colon on the if line if they worked over 40 hours is not a command if (hours > 40) { pay = pay + } Remember the Format command in NetBeans! It will do the indentation for you.

  6. if Control Example System.out.print("Hours this week: "); hours = kbd.nextDouble(); kbd.nextLine(); pay = rate * hours; if (hours > 40) { System.out.println("You get overtime pay."); pay = pay + rate * 0.5 * (hours 40); } Condition Conditional Actions Hours this week: 30 Hours this week: 45 You get overtime pay. no overtime pay overtime pay

  7. Simple Comparisons if (hours > 40) if hours is greater than 40 Can also put if in front of these: a == b a is equal to b a != b a is not equal to b a < b a is less than b a <= b a is less than or equal to b a > b a is greater than b a >= b a is greater than or equal to b You can t use the or signs in Java. It doesn t understand them!

  8. Important Difference Checkwhether a is equal to b: a == b two equals signs Make a equal to b: a = b one equals sign Do not get them confused hours == kbd.nextDouble(); not a statement ! if (hours = 40.0) { incompatible types: double cannot be converted to boolean !

  9. Exercises Write if statements: if grade is greater than or equal to 50, print out You passed! if age is less than 18, print out I m sorry, but you re not allowed to see this movie. if guess is equal to secretNumber, print out You guessed it! if y plus 9 is less than or equal to x times 2, set z equal to zero.

  10. Sequential if Controls Each if is separate if (midtermGrade < 50) { System.out.println("You failed the midterm! "); } if (finalGrade < 50) { System.out.println("You failed the final! "); } You failed the midterm! You failed the final! both You failed the midterm! You failed the final! one other neither

  11. Sequential if Controls Each if is separate if (grade < 50) { System.out.println("I m sorry. You failed."); } if (grade > 90) { System.out.println("That is an excellent grade!"); } What grade did you get? 41 I m sorry. You failed. What grade did you get? 95 That is an excellent grade! one other What grade did you get? 75 neither

  12. Sequential if Controls Each if is separate if (grade >= 50) { System.out.println("You passed."); } if (grade < 80) { System.out.println("You didn t get an A."); } What grade did you get? 41 You didn t get an A. What grade did you get? 95 You passed. one other What grade did you get? 75 You passed. You didn t get an A. both

  13. Exercise What is the output of the following code? int age = 24; int height = 180; int weight = 70; int income = 120000; if (age < 18) { if (height > 180) { if (weight <= 50) { if (income >= 100000) { System.out.println("Young!"); } System.out.println("Tall!"); } System.out.println("Thin!"); } System.out.println("Rich!"); }

  14. Making a Choice Taking a lunch order at Greesieberger s ask what sandwich they want add that sandwich to the order ask if they want fries with that if they say yes: add fries to the order ask what drink they want add that drink to the order Sometimes fries are added to the order; sometimes they re not. Depends on what the user wants.

  15. Choosing Fries Ask the user: Do you want fries with that? Get user s answer (should be yes or no) if the answer was yes, add fries to the order In Java (but not right) System.out.print("Do you want fries? "); String answer = kbd.next(); kbd.nextLine(); if ("yes" == answer) Comparing Strings using == or != !

  16. Object Variables Strings are objects == means Are they the very same object? as in My car and my wife s car are the same car want Are they the same value? as in I have the same car as my neighbour My Car My Wife s Car My Neighbour s Car The String in the code What the user typed in "yes" "yes"

  17. Objects and Primitives Strings are objects String name = "Mark"; Scanners are objects, too Scanner kbd = new Scanner(System.in); Data type name starts with a Capital Letter String, Scanner, Car, Color, NOTE: the variable name starts with a small letter name, kbd, Data types without capitals are primitives int, double,

  18. Talking to Objects You can talk to an object: Hey, kbd, give me the next int. kbd.nextInt(); Hey, kbd, give me the next line. kbd.nextLine(); object name, dot, request name, parentheses Also known as calling a method nextInt and nextLine are methods each returns a value that your program can use

  19. Comparing Strings Ask one String about the other String don t use ==, !=, <, <=, >, >= they don t work (or they do the wrong thing) == oneString.equals(anotherString) != ! oneString.equals(anotherString) < oneString.compareTo(anotherString) < 0 <= oneString.compareTo(anotherString) <= 0 > oneString.compareTo(anotherString) > 0 >= oneString.compareTo(anotherString) >= 0 We won t use compareTo very often in CSCI 1226.

  20. String Equality Strings are equal if exactly the same "First String".equals("First String") Any other strings are different! "First String".equals("Second String") "First String".equals("first string") "First String".equals("FirstString") "First String".equals("First String ") Exercise: In each of the false conditions above, what s different between the Strings? true false false false false

  21. Choosing Fries In Java System.out.println("Do you want fries? "); String answer = kbd.next(); kbd.nextLine(); if ("yes".equals(answer)) only accepts yes does not accept Yes , YES , NOTE: We could have asked answer if it was equals to yes : answer.equals("yes") We d get the same answer.

  22. String.equalsIgnoreCase Sometimes don t care if capital or small "First String".equalsIgnoreCase("First String") "First String".equalsIgnoreCase("first string") Any other strings are different! "First String".equalsIgnoreCase("Second String") "First String".equalsIgnoreCase("FirstString") "First String".equalsIgnoreCase("First String ") true true false false false

  23. Choosing Fries In Java System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if ("yes".equalsIgnoreCase(answer)) accepts yes , Yes , YES , (does not accept yeah ) Again, we could have asked answer about yes : answer.equalsIgnoreCase("yes") We d get the same answer.

  24. String.startsWith Accept any answer starting with y as yes System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.startsWith("y")) Accepts yes , yeah , yup , but not Yes sadly, there is no startsWithIgnoreCase method There s also an endsWith method. And lots of others! Google java string.

  25. String.toUpperCase/toLowerCase Ask a string for upper/lower case version System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); String upperAnswer = answer.toUpperCase(); if (upperAnswer.startsWith("Y")) now accepts Yes , yes , Yeah, yup , upperAnsweris YES , YES , YEAH , YUP answeris still Yes , yes , Yeah , yup

  26. String.oneThing().another() Can combine two steps into one and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.toUpperCase().startsWith("Y")) if answer is yes , then answer.toUpperCase() is YES , and thatdoes start with a Y This works because answer.toUpperCase() is another String. We can ask anyString a question, even if we haven t given it a name.

  27. Scanner.oneThing().another() Can save the String in upper case to start with and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next().toUpperCase(); kbd.nextLine(); if (answer.startsWith("Y")) change user s answer to upper case before saving it user enters yes ; answer is YES user enters Yup ; answer is YUP This works because kbd.nextLine() is another String. We asked kbd to give us the next line, and it gives us back a String.

  28. Exercise Right now we accept anything that starts with the letter Y (capital or small) if (answer.toUpperCase().startsWith("Y")) accepts You need to speak louder as Yes it starts with the letter Y Change the code so that it only accepts abbreviations of YES as Yes . but still allow capital letters Y, y, YE, ye, YES, yes, Ye, yE, YeS, Yes, HINT: we still need to use startsWith and toUpperCase. But who do we ask, and what do we ask about?

  29. The if-else Control Do exactly one of two things if (grade < 50) { System.out.println("You cannot continue to 1227. "); }else { System.out.println("You can continue to 1227! "); } note the indentation What grade did you get? 41 You cannot continue to 1227. What grade did you get? 95 You can continue to 1227! one other

  30. The if-else Control Java syntax: if (condition) { ifSoAction; } else { otherwiseAction; } Does exactly one of those two things two-way choice do this or do that if is one-way choice do this or not

  31. Better Than Two if Controls Could rewrite if-else into two if controls: if (grade < 50) { System.out.println("You cannot continue to 1227. "); } if(grade >= 50) { System.out.println("You can continue to 1227! "); } but that s error-prone makes it more likely you ll make a mistake

  32. Error-Prone Version What s wrong with this: if (grade < 50) { System.out.println("You cannot continue to 1227. "); } if(grade > 50) { System.out.println("You can continue to 1227! "); }

  33. Error-Prone Version For 1228 you need a 60, so copy the code, change 1227 to 1228, and 50 to 60 if (grade < 60) { System.out.println("You cannot continue to 1228. "); } if(grade >= 50) { System.out.println("You can continue to 1228! "); } what went wrong?

  34. Binary Choices Else is for either-or situations either you pass or you fail no program option for incomplete either you can proceed or you cannot either go left or go right no program option for straight State the condition once Split options between if-body and else-body

  35. Exercise Write if-else controls for if temp is over 30, print Go swimming ; otherwise print Play video games if count is zero, print sum divided by count; otherwise print No numbers entered . if answer starts with a y (or Y), then set price to $10; otherwise set it to $15. if num is even, set it equal to n divided by 2; otherwise set it to n times 3, plus 1 num is even num % 2 == 0

  36. if or if-else? Look at the possible outcomes: outcome #1 computer prints A B C D outcome #2 computer prints A D code: System.out.print("A "); if (something) { System.out.print("B "); System.out.print("C "); } System.out.print("D "); Sometimes prints B and C; Sometimes doesn t: (if control)

  37. if or if-else? Look at the possible outcomes: outcome #1 computer prints A B D outcome #2 computer prints A C D code: System.out.print("A "); if (something) { System.out.print("B "); } else { System.out.print("C "); } System.out.print("D "); Sometimes prints B; Sometimes prints C: (if-else control)

  38. Exercise Possible outcomes: outcome #1: A B C E F outcome #2: A D E F What is the code? Possible outcomes: outcome #1: A B C D outcome #2: A B What is the code?

  39. Exercise Possible outcomes: outcome #1: A B C F G outcome #2: A D E F G outcome #3: A B C F outcome #4: A D E F What is the code?

  40. A Common Mistake Putting braces around everything after if if (thisIsTrue) { doThis(); andThat(); else thisOther(); } 'else' without 'if' ! the else must be after the closing brace of the if otherwise can t find the if it s the else for

  41. if-else inside if-else What time is it? 9 pm Good evening! What time is it? 9 am Good morning! M E Evening: 6pm to 11pm. Morning: 7am to 11am. What time is it? 3 pm Good afternoon! What time is it? 3 am Good grief! A G Afternoon: 12pm to 5pm. 12am to 6 am. pm am

  42. Get the Time // create variables Scanner kbd = new Scanner(System.in); int hour; String amPM; // get the time System.out.println("What time is it?"); hour = kbd.nextInt(); // fix weird clock if (hour == 12) { hour = 0; } // NOTE: read next word in lower case amPM = kbd.next().toLowerCase(); kbd.nextLine(); // read the Enter key!

  43. Print the Message // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } A E M G

  44. 9 AM Message // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } "am".equals("pm")? NO 9 > 6? YES

  45. Note Indentation 8 12 16 // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } Remember the Format command!

  46. if inside if You can put if controls inside if controls if first condition is true, test second condition System.out.println("A"); if (condition1) { System.out.println("B"); if (condition2) { System.out.println("C"); } } A AB ABC possible output: pattern: always A sometimes B when B, sometimes C

  47. Eligible for Pension Who is eligible for a pension seniors (age is 65+) disabled people 55+ who live on their own Only ask question if need to know ask age if 65+ eligible if 55+ and not already eligible ask if disabled if disabled ask if live on own if live on own eligible

  48. Eligible for Pension // ask age System.out.print("How old are you? "); age = kbd.nextInt(); kbd.nextLine(); eligible = (age >= 65); // if 55..64, ask if disabled if (age >= 55 && !eligible) { System.out.print("Are you disabled? "); answer = kbd.nextLine().toLowerCase(); // if disabled, ask if live on own if (answer.startsWith("y")) { System.out.print("Do you live on your own? "); answer = kbd.nextLine().toLowerCase(); eligible = answer.startsWith("y"); } }

  49. Exercise Write nested if/if-else to generate: either "A", "AB", "ABC" or "ABD" either "A", "ABC" or "AC" either "A", "ABC", or "D"

  50. Logical Operators p and q both true (0 < n) && (n < 100) either p or q (or both) are true (m > 0) || (n > 0) p is not true !answer.equals("yes") p && q p || q !p

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#