Navigation menu
3.1 Boolean Expressions
Java’s relational operators
- equal to: ==
- not equal to: !=
- less than: <
- greater than: >
- less than or equal to: <=
- greater than or equal to >=
Hack!
int myAge = 15;
int otherAge = 45;
using these integers, determine weather the following statements are True or False
Strings
whats wrong with this code? (below)
String myName = Alisha;
myName != Anika;
myName == Alisha ;
| String myName = Alisha;
cannot find symbol
symbol: variable Alisha
comparison of string objects should be done using String methods, NOT integer methods.
- .equal
- compare to
String myName = "Alisha";
boolean areNamesEqual = myName.equals("Alisha");
if (areNamesEqual) {
System.out.println("True");
} else {
System.out.println("False");
}
True
homework question
what is the precondition for num?
3.2 If Statements and Control Flow
popcorn hack
create test cases that do not satisy the condition above. you can copy/paste the code into the new code cell
public static void main(String[] args) {
int myAge = 16;
System.out.println("Current age: " + myAge);
if (myAge >= 16) {
System.out.println("You can start learning to drive!");
}
System.out.println("On your next birthday, you will be " + (myAge + 1) + " years old!");
}
3.3 If Else Statements
Purpose of Else Statements
Else statements: Handles what happens when the if condition is false. Structure of If-Else:
- If statement with a condition.
- Else statement without a condition.
- Both parts have code blocks surrounded by {}.
- Based on this code, if you were younger than 16 what would it print out?
- Write your own if else statement
3.4 Else If Statements
Else If Statements: Used when you have multiple conditions that need to be checked sequentially.
Flow of Execution: Each condition is evaluated in the order written. The first true condition’s code runs, and the rest are skipped.
Structure:
- Start with a single if statement.
- Follow with as many else if statements as needed.
- Optionally end with one else to handle any remaining cases. Key Concept: The order of conditions matters. More specific conditions should come before broader ones to ensure accurate results.
- If I was 19 what would it print out?
- If I was 13 what would it print out?
- Create your if statement with one else if condition.
3.5 + 3.6 Compund Boolean expressions + Equivalent Boolean Expressions
Nested conditional statements
definition: if statements within other if statements
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get user input for age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Get user input for student status
System.out.print("Are you a student? (yes/no): ");
String studentResponse = scanner.next().toLowerCase();
boolean isStudent = studentResponse.equals("yes");
// Outer if-else block
if (age < 18) {
System.out.println("You are a minor.");
} else {
// Nested if-else block
if (isStudent) {
System.out.println("You are an adult student.");
} else {
System.out.println("You are an adult.");
}
}
scanner.close();
}
}
common mistake: Dangling else
- Java does not care about indentation
- else always belongs to the CLOSEST if
- curly braces can be use to format else so it belongs to the FIRST 'if'
Popcorn hack
- explain the purpose of this algorithm, and what each if condition is used for
- what would be output if input is
- age 20
- anual income 1500
- student status: yes
function checkMembershipEligibility() {
// Get user input
let age = parseInt(prompt("Enter your age:")); // Age input
let income = parseFloat(prompt("Enter your annual income:")); // Annual income input
let isStudent = prompt("Are you a student? (yes/no):").toLowerCase() === 'yes'; // Student status input
// Initialize an empty array to hold results
let results = [];
// Check eligibility for different memberships
// Basic Membership
if (age >= 18 && income >= 20000) {
results.push("You qualify for Basic Membership.");
}
// Premium Membership
if (age >= 25 && income >= 50000) {
results.push("You qualify for Premium Membership.");
}
// Student Discount
if (isStudent) {
results.push("You are eligible for a Student Discount.");
}
// Senior Discount
if (age >= 65) {
results.push("You qualify for a Senior Discount.");
}
// If no eligibility, provide a default message
if (results.length === 0) {
results.push("You do not qualify for any memberships or discounts.");
}
// Output all results
results.forEach(result => console.log(result));
}
// Call the function to execute
checkMembershipEligibility();
3.7 Comparing Objects
short-circuited evaluation:
expression can be determined by only looking at the first operand.
function isEven(num) {
return num % 2 === 0;
}
function isPositive(num) {
return num > 0;
}
let number = 10;
// Short-circuit with &&
if (isEven(number) && isPositive(number)) {
console.log(number + " is even and positive.");
} else {
console.log(number + " does not meet the criteria.");
}
Short-Circuit Behavior:
- && (Logical AND): The expression isEven(number) && isPositive(number) is evaluated.
- JavaScript first evaluates isEven(number). - If this returns false, the whole expression will short-circuit, and isPositive(number) will not be evaluated.
- If isEven(number) is true, then isPositive(number) is evaluated.
Comparing Objects
In java there are two different methods to compare objects but there is a difference between the == operator and the equals() method.
== operator
This operator verifies if two references refer to the same object in memory, without evaluating the objects’ values or attributes.
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = num1;
Integer num4 = new Integer(100);
System.out.println(num1 == num3); // true (same reference)
System.out.println(num1 == num2); // true (cached integers between -128 and 127)
System.out.println(num1 == num4); // false (different references)
This compares the integer as num1 == num3 because they both equal the same integer so it’s true. num1 == num2 because when they are both assigned the value 100 they point to the same reference so they become true. num1 == num4 even though they have the same values they are different because it’s a new integer so it becomes false because they don’t have the same reference point.
equals() method
This method checks the values or attributes of two objects. In custom classes, it is commonly overridden to offer a meaningful comparison based on the class’s specific attributes. It focuses on value rather reference points.
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = new Integer(100);
System.out.println(num1.equals(num2)); // true (same value)
System.out.println(num1.equals(num3)); // true (same value)
This compares the values by their objects, not their references. num1.equals(num2) checks if the values are the same between the 2 but since they both have a value of 100 they are equal so it becomes true. This ignores if the objects have the same or different reference point. num1.euals(num3) even though it has a new integer and it’s different from num1 they are still the same because they have the same value so it makes it true.
Popcorn hack
Would the sharons house and my house be the same?
class House {
private String color;
private int size;
public House(String color, int size) {
this.color = color;
this.size = size;
}
// Override equals method to compare House objects by content
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // Check if same object reference
if (obj == null || getClass() != obj.getClass()) return false; // Check if same class
House house = (House) obj;
return size == house.size && color.equals(house.color); // Compare attributes
}
}
public class Main {
public static void main(String[] args) {
House myHouse = new House("green", 150);
House anikasHouse = new House("green", 150);
House sharonsHouse = new House("green", 150);
// Correct comparison using equals()
System.out.println(myHouse.equals(sharonsHouse)); // This should return true
}
}
Homework: Membership Recommendation System
Problem Overview
You are building a membership recommendation system for a fictional company called “Prime Club.” This system will suggest the most suitable membership tier (or tiers) for a user based on their age, annual income, student status, and employment type. There are 4 types of memberships:
Membership Types
- Basic Membership:
- Requirements:
- Age ≥ 18
- Annual income ≥ $20,000
- Requirements:
- Premium Membership:
- Requirements:
- Age ≥ 25
- Annual income ≥ $50,000
- Requirements:
- Student Discount:
- Requirements:
- Must be a student.
- Requirements:
- Senior Discount:
- Requirements:
- Age ≥ 65
- Requirements:
Task Description
Using conditional statements, Boolean expressions, and comparison techniques you’ve learned, write a Java program that:
- Prompts the user to input the following:
- Age (as an integer)
- Annual income (as a double)
- Student status (yes or no)
- Employment type (full-time, part-time, unemployed)
- Based on these inputs, your program should print out all membership tiers and discounts the user qualifies for. If the user does not qualify for any membership or discount, the program should print:
“You do not qualify for any memberships or discounts.”
Additional Challenge
Add a final recommendation where your program prioritizes the “best” membership for the user if they qualify for multiple memberships (use an else-if
structure).
The best membership should be decided based on the following priorities:
- Premium Membership (highest priority)
- Senior Discount
- Student Discount
- Basic Membership (lowest priority)
Hints (click to reveal)
1. **Input Validation:** - Ensure that age is a positive integer, and annual income is a positive double. - Student status input should be case-insensitive ("yes" or "no"). - Employment type should be one of: "full-time", "part-time", or "unemployed." 2. **Conditions to Consider:** - Use `if-else` statements to check for membership qualifications. - Remember to handle multiple conditions where a user qualifies for more than one membership. 3. **Recommendation Logic:** - Use `else-if` statements to prioritize the memberships based on the provided hierarchy.Constraints
- Age must be a positive integer.
- Annual income must be a positive double.
- Student status should only accept “yes” or “no” (case-insensitive).
- Employment type should be one of: “full-time”, “part-time”, or “unemployed.”
Senior Discount:
Requirements: Age ≥ 65 Task Description: Using conditional statements, Boolean expressions, and comparison techniques you’ve learned, write a Java program that:
Prompts the user to input the following:
Age (as an integer) Annual income (as a double) Student status (yes or no) Employment type (full-time, part-time, unemployed) Based on these inputs, your program should print out all membership tiers and discounts the user qualifies for. If the user does not qualify for any membership or discount, the program should print out: “You do not qualify for any memberships or discounts.”
Additional Challenge: Add a final recommendation where your program prioritizes the “best” membership for the user if they qualify for multiple memberships (use an else-if structure).
The best membership should be decided based on the following priorities: Premium Membership (highest priority) Senior Discount Student Discount Basic Membership (lowest priority) Constraints: Age must be a positive integer. Annual income must be a positive double. Student status should only accept “yes” or “no” (case-insensitive). Employment type should be one of: “full-time”, “part-time”, or “unemployed.”