CSA Blog

Ian Wu

Unit 3 Boolean - Homework

3.1: Boolean Expressions 3.2: If Control Flow 3.3: If Else 3.4: Else If 3.5: Compound Booleans 3.6: Equivalent Booleans 3.7: Comparing Objects 3.8: Homework

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

  1. Basic Membership:
    • Requirements:
      • Age ≥ 18
      • Annual income ≥ $20,000
  2. Premium Membership:
    • Requirements:
      • Age ≥ 25
      • Annual income ≥ $50,000
  3. Student Discount:
    • Requirements:
      • Must be a student.
  4. Senior Discount:
    • Requirements:
      • Age ≥ 65

Task Description

Using conditional statements, Boolean expressions, and comparison techniques you’ve learned, write a Java program that:

  1. 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)
  2. 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:

  1. Premium Membership (highest priority)
  2. Senior Discount
  3. Student Discount
  4. 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.”
import java.util.Scanner; 

Scanner input = new Scanner(System.in);

System.out.println("Enter age");
Integer age = Integer.parseInt(input.nextLine());
System.out.println("Age entered: " + age);

System.out.println("Enter income");
Double income = Double.parseDouble(input.nextLine());
System.out.println("Income entered: " + income);

System.out.println("Enter student status [y/n]: ");
Boolean student = (input.nextLine() == "y") ? true : false;
System.out.println("Student status entered: " + student);

System.out.println("Enter employment status [f/u/p]:");
String es = input.nextLine();
System.out.println("Income entered: " + es);

String[] discounts = new String[4];

if (age > 17 && income > 1999.99) {
    System.out.println("Eligible for Basic Membership");
    discounts[3] = "Basic Membership";
}
if (age > 24 && income > 4999.99) {
    System.out.println("Eligible for Premium Membership");
    discounts[0] = "Premium Membership";
}
if (student) {
    System.out.println("Eligible for Student Discount");
    discounts[1] = "Student Discount";
}
if (age > 64) {
    System.out.println("Eligible for Senior Discount");
    discounts[2] = "Senior Discount";
}

for (int i=0;i<4;i++) {
    if (discounts[i] != null) {
        break;
    }
    if (i == 3) {
        System.out.println("You do not qualify for any memberships or discounts");
    }
}

for (int j=0;j<4;j++) {
    if (discounts[j] != null) {
        System.out.println("Best discount/membership: " + discounts[j]);
        break;
    }
}
Enter age


Age entered: 1000
Enter income
Income entered: -20.0
Enter student status [y/n]: 
Student status entered: false
Enter employment status [f/u/p]:
Income entered: f
Eligible for Senior Discount
Best discount/membership: Senior Discount

Unit 2 — Wrapper Classes & Math Module

Objects and Void Methods Methods String Objects Wrapper Classes HW

Lesson 2.8: Wrapper Classes! 🍫

Introduction

By now, you should be used to working with different variables and data types in Java. Some of you may have asked a question regarding why the data type String has a capital S, while int is not capitalized.

The answer is: String is a reference type, while int is a primitive type.

Primitive types are the mosic basic data types in Java, and they always represent single values. On the other hand, Reference types are used to store objects and can have a variety of things stored.

Important Wrapper Classes 🔢🔠

  • Integer for int
  • Double for double

These classes are part of the java.lang package, so you don’t need to import them explicitly. Additionally, there are more wrapper classes, but these are the two that are required by College Board.

But let’s back off real quick. What is a Wrapper class?

Answer: A wrapper class allows you to use primitive data types.

Integer Wrapper Class 🔢

The Integer class wraps a value of the primitive type int in an object.

intmeme

Methods & Constants

  1. Constructor: Integer (int value): Constructs a new Integer object representing the specified int value.
  2. Integer.MIN_VALUE and Integer.MAX_VALUE returns the minimum/maximum value that an int can hold. Going beyound these borders will lead to overflow.
  3. int intValue(): Returns the value of the Integer as an int

Let’s take a look at an example:

public class Main {
    public static void main(String[] args){
        Integer num1 = new Integer(5);  // Constructor usage 

        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
        System.out.println("Maximum value of Integer: " + Integer.MAX_VALUE);
        System.out.println("Minimum value of Integer: " + Integer.MIN_VALUE);
        System.out.println("num1 as int: " + num1.intValue());
    }
}

Double Wrapper Class 📦

The Double class wraps a value of the primitive type double in an object.

Important Methods

  1. Constructor: Double(double value): Constructs a new Double object representing the specified double value.
  2. double doubleValue(): Returns the value of the Double as a double

Let’s take a look at another example.

public class Main {
    public static void main(String[] args){
        Double pi = new Double(3.14159); 
        Double e = Double.valueOf(2.71828);

        System.out.println("pi = " + pi);
        System.out.println("e = " + e);
        System.out.println("pi as double: " + pi.doubleValue());
    }
}

Autoboxing and Unboxing

Java gives you automatic conversion between primitive types and their respective wrapper classes

  • Autoboxing: Primitive Value ➡️ Wrapper Object
  • Unboxing: Wrapper object ➡️ Primitive Value

model

Let’s take a look at a short example.

public class BoxDemo {
    public static void demo(String[] args) {
        Integer wrapped = 100;  // Autoboxing
        int unwrapped = wrapped;  // Unboxing

        System.out.println("📦wrapped = " + wrapped);
        System.out.println("unwrapped = " + unwrapped);
    }
}

BoxDemo.demo(new String[]{});

Practice Exercises

Fix the code below!


Integer num1 = 50;
Integer num2 = new Integer(75);

Double d1 = 3.14;
double d2 = new Double(2.718);

System.out.println("Sum of integers: " + (num1 + num2));
System.out.println("Product of doubles: " + (d1 * d2));
Sum of integers: 125
Product of doubles: 8.53452

Now, complete the exercise below without any extra help.


// TODO: Create an Integer object using autoboxing
int integer = 0;

// TODO: Create a double primitive from a Double object (unboxing)
double d0uble = new Double(891.12);

// TODO: Print both values
System.out.println(integer);
System.out.println(d0uble);
0
891.12

2.9: Using the Math Module 📝

Have you ever been stuck in your Calculus or Physics class because your calculator died?

mathmeme

You can use the Java math module to help you 😁!

Introduction

The Java math module is a package that comes with java.lang.Math. All it’s methods are static.

This is more straightforward than wrapper classes, but still important to know.

Useful Methods

  1. static int abs(int x): Returns the absolute value of an int
  2. static double abs(double x): Returns the absolute value of a double
  3. static double pow(double base, double exponent): Returns the value of the first value raised to the power of the second value
  4. static double sqrt(double x): Returns the (positive) square root of a double value
  5. static double random(): Returns a double greater than or equal to 0.0 and less than 1.0

Let’s take a look at a code example using all of these!

public class Main {
    public static void main(String[] args) {
        // abs() method for int and double
        int intNumber = -5;
        double doubleNumber = -10.5;
        System.out.println("Absolute value of " + intNumber + " is: " + Math.abs(intNumber));
        System.out.println("Absolute value of " + doubleNumber + " is: " + Math.abs(doubleNumber));

        // pow() method
        double base = 2.0;
        double exponent = 3.0;
        System.out.println(base + " raised to the power of " + exponent + " is: " + Math.pow(base, exponent));

        // sqrt() method
        double number = 16.0;
        System.out.println("Square root of " + number + " is: " + Math.sqrt(number));

        // random() method
        System.out.println("A random number between 0.0 and 1.0: " + Math.random());
    }
}

PRACTICE

Let’s try a practice! Fill in the function below, randomize, following the steps below:

  1. Take the absolute value of both numbers
  2. Return a random number in between those two numbers, inclusive
import java.util.*;
public static double randomize(double a, double b){
    return (double) (Math.random() * (b - a)) + a;
}


Scanner scan = new Scanner(System.in);
double a = scan.nextDouble();
double b = scan.nextDouble();

System.out.println(randomize(a, b));
26.3101834015585