Intro CS - Ch.5 - if-else
5.1.5 Increment and Decrement Operators
5.2 Intro to “ if ” statements
5.4 Intro to “ if - else if - else “:
CH. 5 PROJECT: Choose your own adventure
5. if-else
5.1 Operators
- Operators are used to perform operations on variables and values. We use the + operator to add together two values. We could use the > operator to compare two values to see if one is greater than another.
- There are many different types of operators that will be introduced here.
5.1.1 Arithmetic Operators
- These are straightforward and follow PEMDAS order of operations, with modulus (%) on the same level as division and multiplication
5.1.2 Relational Operators
- These are used in boolean expressions, also known as conditionals, that evaluate to true or false.
- Be careful when comparing floating point values (doubles). The computer has trouble representing them exactly and this can lead to trouble.
- Don’t use “==” to compare two Strings. We will understand why later in the course. Instead, do this:
To compare two Strings named name1 and name2, do this:
name1.equals(name2) // this will result in true or false
Don’t do this:
name1 == name2 // this result will not be dependable
5.1.3 Logical Operators
- Logical operators can form compound boolean expression such as:
x < 4 AND y > 5 OR age == 21
- Values of “true” and “false” are assigned by the truth tables:
5.1.4 Assignment Operators
5.1.5 Increment and Decrement Operators
- The difference of i++ vs ++i can be seen in the following example:
If i has a value of 5:
System.out.println(i++); // Will print 5 and then increment i to 6.
System.out.println(++i); // Will increment i to 6 and then print 6.
5.1.6 Operator Precedence
Operator worksheet #1
Operator worksheet #2
5.2 Intro to “ if ” statements
- You can have a program do something “ if ” a condition is TRUE. If it is FALSE, it will not do it.
- The syntax: If there is only one statement to be executed in the “ if ”, then you don’t need curly brackets, but I put them in all the time for good practice.
- Don’t put a semicolon at the end of the statement with the “if” in it.
EXAMPLE:
int x = 10;
if (x < 8) // No semicolon!
{
System.out.println(“x is less than 8!”);
}
System.out.println(“This is the end of the program.”);
OUTPUT: This is the end of the program.
EXAMPLE:
int x = 3;
if (x < 8) // No semicolon!
{
System.out.println(“x is less than 8!”);
}
System.out.println(“This is the end of the program.”);
OUTPUT: x is less than 8!
This is the end of the program.
- Structure of an “if”
if (conditional) // conditional needs to evaluate to TRUE or FALSE
{
// code executed if condition is true
}
5.3 Intro to if-else:
- It’s all based on boolean values. TRUE or FALSE. If something is TRUE, do something. If something is FALSE, do something ELSE.
- Basic structure:
if (conditional)
{
// code to execute when conditional is TRUE
}
else
{
// code to execute when conditional is FALSE
}
EXAMPLE:
int x = 5;
if (x < 8)
{
System.out.println(“x is less than 8!”);
}
else
{
System.out.println(“x is greater than 8!”);
}
System.out.println(“This is the end of the program.”);
OUTPUT: x is less than 8!
This is the end of the program
EXAMPLE:
int x = 20;
if (x < 8)
{
System.out.println(“x is less than 8!”);
}
else
{
System.out.println(“x is greater than 8!”);
}
System.out.println(“This is the end of the program.”);
OUTPUT: x is greater than 8!
This is the end of the program
5.4 Intro to “ if - else if - else “:
- Like an “if-else” but with more than two possibilities. Can have as many else-ifs as you want.
- Once one of the conditions is TRUE, the other ones are skipped. This is one entire logic block. You don’t need to keep checking once one of the conditions is TRUE.
- Basic structure:
if (conditional #1)
{
// code to execute when conditional #1 is TRUE
}
else if (conditional #2)
{
// code to execute when conditional #2 is TRUE
}
else if (conditional #3)
{
// code to execute when conditional #3 is TRUE
}
else // The else is optional
{
// code to execute when all conditions above are FALSE
}
EXAMPLE:
int age = 78;
if (age > 0 && age < 12)
{
System.out.println(“One CHILD ticket.”);
}
else if (age > 11 && age < 65)
{
System.out.println(“One ADULT ticket.”);
}
else if (age > 64 && age < 150)
{
System.out.println(“One SENIOR ticket.”);
}
else
{
System.out.println(“You can’t be over 150 years old!!”);
}
OUTPUT: One SENIOR ticket.
5.5 Intro to Nested “ if ”
- The statement executed as a result of an if statement could be another if statement. This is called a “nested if”. It lets us make another decision after getting the results of a previous decision.
- Basic structure of a simple nested if:
if (conditional #1)
{
if (conditional #2)
{
// code to execute when conditional #1 and #2 are TRUE
}
else
{
// code to execute when conditional #1 is TRUE and #2 is FALSE
}
}
else
{
// code to execute when conditional #1 is FALSE
}
EXAMPLE: Bowling score report
int points = 122, frame = 4;
if (points < 100)
{
if (frame < 5)
{
System.out.println(“Your score is low, but it’s early in the game!”);
}
else
{
System.out.println(“Your score is low, catch up quick!”);
}
}
else
{
if (frame < 5)
{
System.out.println(“You have a high score for this early in the
game!”);
}
else
{
System.out.println(“That’s a solid score for late in the game.”);
}
}
OUTPUT: You have a high score for this early in the game!
Chapter 5: Assignments
A5.1 The first “ if “
Create a program that asks the user how many languages they speak. The program should respond with “Wow. That’s a lot!” only if the user speaks three or more languages.
PROGRAM STRUCTURE:
// import java.util.Scanner; at the very top of the program
// Create a scanner to receive input at the top of the main method
// Scanner userInput = new Scanner(System.in);
//
// Ask the user how many languages they speak
// Assign the input to an int variable called numLang
// numLang = userInput.nextInt();
//
// Use an if statement to determine if the input is greater than 2:
// if (conditional to check for numLang being greater than 2)
// {
// print: Wow. That’s a lot!
// }
//
// print: Thank you.
//
// Close the Scanner at the end of the main method:
// userInput.close();
SAMPLE RUN #1:
How many languages do you speak?
3
Wow. That’s a lot!
Thank you.
SAMPLE RUN #2:
How many languages do you speak?
1
Thank you.
A5.2 Road Trip Checklist
Create a program that runs through a checklist of items before heading out on a road trip. This should include gas in the tank, miles since the last oil change, check air pressure in the tires, and if there is any washer fluid.
PROGRAM STRUCTURE:
// Use the overall program structure from the last exercise
//
// Use “if” statements for the next four questions:
// Ask the user “How many gallons of gas are in the tank?”
// If the answer is less than 10, say “BETTER FILL UP!”
//
// Ask the user “How many miles since the last oil change?”
// If the answer is more than 5000, say “CHANGE THE OIL!”
//
// Ask the user “Have you checked the air pressure in the tires?”
// If the answer is “No”, say “BETTER CHECK THE TIRES!”
// (Remember not to use == with Strings)
//
// Ask the user “Do you have washer fluid?”
// If the answer is “No”, say “GET SOME WASHER FLUID!”
//
// Print: Have a good trip!
SAMPLE RUN #1:
How many gallons of gas are in the tank?
3
BETTER FILL UP!
How many miles since the last oil change?
2000
Have you checked the air pressure in the tires?
No
BETTER CHECK THE TIRES!
Do you have washer fluid?
Yes
HAVE A GOOD TRIP!
SAMPLE RUN #2:
How many gallons of gas are in the tank?
13
How many miles since the last oil change?
14,000
CHANGE THE OIL!
Have you checked the air pressure in the tires?
No
BETTER CHECK THE TIRES!
Do you have washer fluid?
No
GET SOME WASHER FLUID!
HAVE A GOOD TRIP!
A5.3 Hi / Low
This program should ask the user for a number. It will then tell the user if the number is greater than or less than 100. The “Thank you” at the end should not be in the if-else blocks. This program doesn’t work for input that is 100. Why? This will be taken care of in a later assignment.
PROGRAM STRUCTURE:
// This program is similar to 5.1 but will have an “if - else”:
// Use an “if - else” to determine if the input is above or below 100:
// if (conditional to check for less than 100)
// {
// print: That number is lower than 100.
// }
// else
// {
// print: That number is greater than 100.
//
// print: Thank you.
SAMPLE RUN #1:
Please enter a number:
45
That number is lower than 100.
Thank you.
SAMPLE RUN #2:
Please enter a number:
1500
That number is greater than 100.
Thank you.
A5.4 Password with one chance
The user has one chance to get the password or they are not allowed in. In the program, you will set the password as: 5656.
PROGRAM STRUCTURE:
// This program is similar to 5.3 using an if-else statement
SAMPLE RUN #1:
Please give me the password. It is a four digit number. You have one chance!
5656
You may enter….
SAMPLE RUN #2:
Please give me the password. It is a four digit number. You have one chance!
2345
You may NOT enter….
A5.5 Modulus Quiz
This program will pose two questions to the user to test them on their knowledge of modulus calculations. You will make up these questions yourself and other students will test themselves with your program. A True or False question will be posed. That answer will be evaluated.
PROGRAM STRUCTURE:
// First question:
// If (check for correct answer being TRUE)
// {
// That is correct!
// }
// else
// {
// That is wrong!
// }
// Second question:
// If (check for correct answer being TRUE)
// {
// That is correct!
// }
// else
// {
// That is wrong!
// }
SAMPLE RUN:
I will ask you a question, and you will tell me if it’s TRUE or FALSE:
The value of 14%10 is 4? (TRUE or FALSE)
true
That is correct!
Here is your second questions. Tell me if it’s TRUE or FALSE:
The value of 5%6 is 0? (TRUE or FALSE)
true
That is wrong!
A5.6 Hi Low Equals
This is similar to 5.3 but you need to use an else-if because three cases are being evaluated. This program should ask the user for a number. It will then tell the user if the number is greater than 100, equal to 100, or less than 100.
SAMPLE RUN #1:
Please enter a number:
89
That number is lower than 100.
Thank you.
SAMPLE RUN #2:
Please enter a number:
110
That number is greater than 100.
Thank you.
SAMPLE RUN #3:
Please enter a number:
100
100! That number is the same as ten to the power of two!
Thank you.
A5.7 Flipper rental fitting
Write a program that recommends the appropriate flipper size that should be rented based on your shoe size. The following recommendations should be made:
0-5 - small
6-9 - medium
10 -14 - large
14 and above - No flippers available
SAMPLE RUN #1:
What size is your shoe?
5
You need small flippers.
SAMPLE RUN #2:
What size is your shoe?
11
You need large flippers.
SAMPLE RUN #3:
What size is your shoe?
16
We have no flippers for you.
A5.8 Driving Questionnaire
Create a series of questions that involve nested ifs. Use the sample runs below for details.
PROGRAM STRUCTURE:
// if (check for 16 or older is TRUE)
// {
// print: Do you have a driver’s license?
// if (check for driver’s license is FALSE)
// {
// Print: I guess I will drive!
// }
// else
// Print: You drive!
// }
// else
// {
// print: Get in the back seat
// }
SAMPLE RUN #1:
Are you 16 or older? (1 = Yes, 2 = No)
Yes
Do you have your driver’s license? (1 = Yes, 2 = No)
No
I guess I will drive!
SAMPLE RUN #2:
Are you 16 or older? (1 = Yes, 2 = No)
No
Get in the back seat!
A5.9 Buying a Ticket
This program will determine the price of a ticket based on the age. There are Child, Adult and Senior ticket prices.
PROGRAM STRUCTURE:
// if (check if between 18 and 65 years old is TRUE)
// {
// print: You will be charged an adult fare
// }
// else
// {
// print: Are you a child or senior?
//
// if (check for child is TRUE)
// {
// Print: You will be charged a child fare
// }
// else
// Print: You will be charged a senior fare
// }
SAMPLE RUN #1:
Are you between 18 and 65 years old? (1 = Yes, 2 = No)
1
You will be charged an adult fare.
SAMPLE RUN #2:
Are you between 18 and 65 years old? (1 = Yes, 2 = No)
2
Are you a (1) child or (2) senior?
1
You will be charged a child fare
CH. 5 PROJECT: Choose your own adventure
This project will require you to create your own “choose your own adventure” story. The structure of the program will be based on nested ifs. The reader gets to choose between two options at each stage of the story. There should be at least three choices for each path through the story as described in the tree structure below.
IMPORTANT: Use methods for each part of the story. The main method should not include any of the actual story content but should only have the simple structure of the story. Each time a choice is made by the user, a method is called to print the next section to the screen.
STRUCTURE:
The opening of the story should have two options (1 and 2)
Options 1 and 2 should each have 2 options (1a, 1b and 2a, 2b)
Each of those options should have 2 options (1aa, 1ab and 1ba, 1bb and 2aa, 2ab and
2ba, 2bb)
You can make the story longer if you wish, but it must have this structure at least.
Opening
/ \
1 2
/ \ / \
1a 1b 2a 2b
/ \ / \ / \ / \
1aa 1ab 1ba 1bb 2aa 2ab 2ba 2bb
SAMPLE RUN:
You wake up to find yourself in a room. The door is locked. What do you do?
- Bang on the door for help
- Investigate what is in the room
If the user chooses 1:
Someone comes to the other side of the door and says: “I can’t open the door. I
have to call the fire department. Can you try to climb out the ceiling?”
- Answer yes and try to climb out the ceiling.
- Answer no and wait for the fire department
If the user chooses 2:
You look around the room and find an envelope. You open it and in it is a picture
of a man holding a sign that says: “If you are reading this, you are in trouble.
Follow my directions carefully. First thing, no matter what, don’t open the cabinet.” You look around and see a cabinet. Do you open it?
- Yes
- No