How to Mix Different Logical Operators Together in Java - dummies

How to Mix Different Logical Operators Together in Java

By Barry Burd

Let’s think about the Java code that would be needed if your local movie theater offers discount coupons. The trouble is, you can’t use a coupon along with any other discount. You tried combining the coupon with the senior citizen discount. That didn’t work.

The theater must use some software that checks for people like me. It looks something like this code.

image0.jpg

import java.util.Scanner;
class CheckAgeForDiscount {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  int age;
  double price = 0.00;
  char reply;
  System.out.print("How old are you? ");
  age = keyboard.nextInt();
  System.out.print("Have a coupon? (Y/N) ");
  reply = keyboard.findWithinHorizon(".", 0)
           .charAt(0);
  if (age >= 12 && age < 65) {
   price = 9.25;
  }
  if (age < 12 || age >= 65) {
   price = 5.25;
  }
  if ((reply == 'Y' || reply == 'y') &&
   (age >= 12 && age < 65)) {
   price -= 2.00;
  }
  System.out.print("Please pay $");
  System.out.print(price);
  System.out.print(". ");
  System.out.println("Enjoy the show!");
  keyboard.close();
 }
}

The big difference here is the bolded if statement. This if statement tests two things, and each thing has two parts of its own:

  • Does the customer have a coupon?

    That is, did the customer reply with either Yory?

  • Is the customer in the regular age group?

    That is, is the customer at least 12 years old and younger than 65?

In the code, you join items 1 and 2 using the && operator. You do this because both items (item 1 and item 2) must be true in order for the customer to qualify for the $2.00 discount.

image1.jpg