Welcome to Lesson 8!Learning Objectives
String student1 = "Tanya"; String student2 = "Tasha"; if (student1.compareTo(student2) < 0) { System.out.println("Alpha"); } else { System.out.println("Beta"); }
2. Logical Operators
System.out.println("Can you guess it?\n"); System.out.print("Enter your guess: "); guess = input.nextInt(); if (guess < 1 || guess > 10) { //if guess is < 1 OR guess > 10 System.out.println("Invalid entry!"); } else if (guess < 7) { System.out.println("Your guess is too low"); } else if (guess > 7) { System.out.println("Your guess is too high"); } else { System.out.println("*** Correct! ***"); } Review of Boolean Variables
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public static void main(String[] args)
{
int num;
|
Introducing &&, || and !
Logical operators and search engines video
Combining Test Conditions with Logical Operators
- A logical operator, or Boolean operator, is an operator that treats operands as Boolean values (
true
orfalse
) - Java has several logical operators, but we only need to use three to create any possible test condition
- These three operators are
and
,or
andnot
, which are discussed below - These logical operators are traditionally written as
&&
(and
),||
(or
) and! (
not
)
Truth Tables for AND, OR and NOT
&&
(AND
) Operator Truth Tableexpr1
expr2
expr1 &&
expr2
Example Result true
true
true
5 < 10 && 5 > 2
true
true
false
false
5 < 10 && 5 < 2
false
false
true
false
5 > 10 && 5 > 2
false
false
false
false
5 > 10 && 5 < 2
false
||
(OR
) Operator Truth Tableexpr1
expr2
expr1 ||
expr2
Example Result true
true
true
5 < 10 || 5 > 2
true
true
false
true
5 < 10 || 5 < 2
true
false
true
true
5 > 10 || 5 > 2
true
false
false
false
5 > 10 || 5 < 2
false
not
(!
) Operator Truth TableIf expr is... Then !
expr is...Example Result true
false
!true
false
false
true
!(5 < 2)
true
Testing Multiple Conditions Using Logical Operators
- Sometimes we need to test for multiple conditions using a single if statement
- In this case, we will need to chain together the two conditions using a logical operator, either && or ||
- Note that one either side of the logical operator there must be a stand alone test condition that resolves to true or false
if (age >= 18 && age <= 25) //Correct!!!
if (age >= 18 && <= 25) //No! Incorrect!!
- For example, we want to test if an age is between 18 and 65
- We need to test that both parts of are true: is the age >= 18 AND is the age <= 65
int age = 0;
System.out.print("Enter your age: ");
age = input.nextInt();
if (age >= 18 && age <= 65)
{
System.out.println("Adult!");
} else {
System.out.println("Child, Teen or Older Adult!");
}
- Another way to use logical operators to test the age is:
int age = 0; System.out.print("Enter your age: "); age = input.nextInt(); if (age < 18 || age > 65) { System.out.println("Child, Teen or Older Adult!"); } else { System.out.println("Adult!"); }
- Many people confuse
&&
and||
conditions, especially when learning about logical operators - A value lies between 18 and 65 if the value is at least 18 and at most 65
- A value is outside that range if it is less than (but not equal to) 18 or greater than (but not equal to) 65
- There is no golden rule; we have to think carefully and test our conditions
Parenthesis
- Remember that Boolean expressions in an
if
statement can be enclosed in parenthesis - Thus, an
if
statement with&&
might look like:if ((guess != GUESS1) && (guess != GUESS2))
- However, relational operators have a higher precedence than logical operators, so the extra parenthesis are not necessary
- As such, we can remove the inner parenthesis without affecting the logical meaning:
if (guess != GUESS1 && guess != GUESS2)
- However, if using parenthesis is easier to understand then use the extra parenthesis
3. Conditional Pitfalls
- Below are some common mistakes when using logical operators.
- Fortunately, Java gives you an error message when you make the below mistakes.
Using = Instead of ==
- One common mistake is to use
=
when you meant to use==
- For example, look at the test condition in the following code:
if (guess = 7) { System.out.println("*** Correct! ***"); } else { System.out.println("Sorry, that is not correct."); }
- Fortunately, if you make this mistake, the Java compiler will not allow your code to run.
- However, if you correctly use == then your code will compile
if (7 == guess) {
Strings of Inequalities
- Do NOT use a string of inequalities like the following:
int a = 5, b = 1, c = 10; if (a < b < c) { System.out.println("b is between a and c"); } else { System.out.println("b is NOT between a and c"); }
- Again, your code will not compile
- Instead, the correct way is to use
&&
as follows:int a = 5, b = 1, c = 10; if (a < b && b < c) { System.out.println("b is between a and c"); } else { System.out.println("b is NOT between a and c"); }
Strings of Logical Operators
- Logical expressions often read like "normal" English.
- However, Java requires more exactness than English
- For example, the following code will compile and run but give wrong results:
int guess; System.out.print("Enter a guess: "); guess = input.nextInt(); if (guess == 7 || 8) { System.out.println("*** Correct! ***"); } else { System.out.println("Sorry, that is not correct."); }
- The above produces an error when you try to compile your code.
- Instead, the correct way is to use
||
as follows:
int guess; System.out.print("Enter a guess: "); guess = input.nextInt(); if (guess == 7 || guess == 8) { System.out.println("*** Correct! ***"); } else { System.out.println("Sorry, that is not correct."); }
Activity 8.1: What's Your Generation? (10 pts)
- There are 6 generations living in America, side-by-side, today.
- Your program will determine to which generation a user belongs.
- )pen up a new project and name it Activity8, and add a new class called Generation
- You will need to take as input the year of his or her birth.
- Then, you will need a series of test conditions (think if - else if - else) to determine the generation of your user.
- You will also need to use logical operators (&&, ||, !).
- Below is a chart with the range of birth years for each generation.
- Note the double quotes around each generation's name. For full credit, you must include the " when you output the generation.
Years of Birth Generation
1900-1927 "The Greatest Generation"
1928-1945 "The Silents"
1946-1964 "The Baby Boomers"
1965-1979 "Generation X"
1980-1999 "The Millennial Generation"
2000-2020 "Generation Z"
- Your goal is to prompt the user for his or her year of birth and then print out a message about which generation he or she belongs to.
- To start, print the following message to the user:
What's your generation?
- Then, you will need a variable to store the user's year of birth:
int year_of_birth;
- Next, prompt your user to enter his or her year of birth with a statement like the following:
Please enter the year of your birth: _
- Subsequently, you will need 6 if and if else statements like the following:
if ( year_of_birth >= 1900 && year_of_birth < 1928)
{
System.out.println("You belong to the \"Greatest Generation\"");
}
else if ( year_of_birth >= 1928 && year_of_birth < 1946)
{
System.out.println("You belong to the \"The Silents\"");
}
{
System.out.println("You belong to the \"Greatest Generation\"");
}
else if ( year_of_birth >= 1928 && year_of_birth < 1946)
{
System.out.println("You belong to the \"The Silents\"");
}
//rest of your else ifs and your else clause go here
- Important: Why are we using && here and not ||?
- Finally, you will need to do some error checking of the user input.
- If the user inputs a date that is either too high or too low, your program must print out the following message:
Invalid entry. Please enter a birth year in the range 1900 - 2020.
- The above should go in your else clause
- Make sure your output is identical to the sample output below before you submit.
- When you are finished, upload Generation.java to Canvas
What's your generation?
Please enter the year of your birth: 1926
You belong to the "Greatest Generation".
Alternately,
What's your generation?
Please enter the year of your birth: 2021
Invalid entry! Please enter a birth year in the range 1900 - 2020.
More Information on Logical Operators
- Domino Addition - Numberphile: Logical operator circuits using dominoes
Wrap up
- Imagine that a local radio station is holding a contest to give away a year's supply of free pet food to one lucky winner.
- To win the contest, you must meet the following criteria:
- You must be caller 19
- The pet your own must be one of the following: dog, cat, rabbit
- You must be between the ages of 18 and 65.
- Which of the following test conditions will correctly determine the winner of the contest
a. if (numCaller == 19 && (pet == "rabbit" || pet == "cat" || pet == "dog") && (age >= 18 && age <= 65))
System.out.println("You are the winner!");
b. if (numCaller == 19 && (pet == "rabbit" || "cat" || "dog") && (age >= 18 && <= 65))
System.out.println("You are the winner!");
c. if (numCaller == 19 || (pet.equals("rabbit") && pet.equals("cat") && pet.equals("dog")) || (age >= 18 && age <= 65))
System.out.println("You are the winner!");
d. if (numCaller == 19 && (pet.equals("rabbit") || pet.equals("cat") || pet.equals("dog")) && (age >= 18 && age <= 65))
System.out.println("You are the winner!");
e. if (numCaller = 19 && (pet.equals("rabbit") || pet.equals("cat") || pet.equals("dog") && (age >= 18) || age <= 65))
System.out.println("You are the winner!");
int age = 20;
boolean is_student = true;
if (is_student || age > 21) {
System.out.println("Fi!");
}
if (!is_student && age < 21) {
System.out.println("Fo!");
}
if (is_student && age < 21) {
System.out.println("Fum!");
}