CISC 1115
Introduction to Programming Using Java
Boolean & Logical Operators


Reading from the Text

Chapter 5

More on Operators

Relational Operators

Java's Relational Operators

Note: to compare Strings, use the equals method (of the String class), rather than ==. (There are other methods for greater, less, etc — we'll cover them later):
String s1, s2;
…
s1 = …
…
s2 = …
…
if (s1.equals(s2))	// NOT s1 == s2
	…
…

Logical Operators

Program P06.1 Vaccines

A medical office has hired us to write a program to screen out patients who should not be receiving the swine flu vaccine. The Department of Health has determined that children under the age of 3 and seniors over the age of 65 should NOT be receiving the vaccine. The program should prompt the user for the patients age and print out whether the vaccine may be administered.

import java.util.*;

public class Vaccines {
        public static void main(String [] args) {
                Scanner scanner = new Scanner(System.in);

                System.out.print("Enter patient's age: ");
                int age = scanner.nextInt();;

                if (age < 3 || age > 65)
                        System.out.println( "***** Do NOT ADMINISTER VACCINE *******");
                else
                        System.out.println( "Go ahead and stick it to 'em");
        }
}

Java's Logical Operators

Note: && has higher precedence than ||.

DeMorgans Laws

The following two laws of logical operators often helps clean up a complex expression (or make it more understandable):

If a and b are conditions, then:

the condition "it is not the case that age is less than or equal to 3 or age is greater than or equal to 65"
if !(age <= 3 || age >= 65)
transforms to (by DeMorgan's Law):
if (!(age <=3) && !(age >= 65))
which then transforms to (through an understanding of the relational operators):
if (age > 3 && age < 65)

Short-circuiting

Program P06.2 — Payroll
Write a program that scans a payroll file for discrepancies. The payroll file-- named payroll.dataconsists of a header value for the number of employees followed by the the following data for each employee: Occasionally, the data entry people make a mistake and enter an annual salary for a part-timer, or an hourly rate for a full-time. No part-timer should have an hourly rate of greater than $50 and similarly, no full-timer earns less than $10,000.

The program should scan the file, and print out the info for any employee whose payroll record seems incorrect.

import java.io.*;
import java.util.*;

public class Payroll {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("payroll.data"));

                int numEmployees = scanner.nextInt();

                for (int i = 1; i <= numEmployees; i++) {

                        int id = scanner.nextInt();
                        String lastName = scanner.next();
                        String firstName = scanner.next();;
                        String status = scanner.next();;
                        int amount = scanner.nextInt();;

                        if (status.equals("f") && amount < 10000 ||
                                        status.equals("p") && amount > 50)
                                System.out.println("Possibly corrupt record for employee " + lastName + ", " + firstName + " (" + id + ")");
                }
        }
}

Program P06.3 — Payroll
Rewrite Program 6.2 so that it calls a method, isDataCorrupt to determine whether the data is possibly corrupt.
import java.io.*;
import java.util.*;

public class Payroll {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("payroll.data"));

                int numEmployees = scanner.nextInt();

                for (int i = 1; i <= numEmployees; i++) {

                        int id = scanner.nextInt();
                        String lastName = scanner.next();
                        String firstName = scanner.next();;
                        String status = scanner.next();;
                        int amount = scanner.nextInt();;

                        if (isDataCorrupt(status, amount) )
                                System.out.println("Possibly corrupt record for employee " + lastName + ", " + firstName + " (" + id + ")");
                }
        }

        public static boolean isDataCorrupt(String status, int amount) {
                if (status.equals("f") && amount < 10000 ||
                                status.equals("p") && amount > 50)
                        return true;
                return false;
        }
}

Type boolean

Given the declarations:
int i, j, k;
double d, e, f;
string s, t, u;
Consider the types of the following expressions:
Expression Type
3 int
4.6 double
"Hello" string
i+j int
i/j int
d/e double
i/d double
s string

But what about

Expression Type
i < j ???
i == 6 ???
d > e && f < 4.8 ???
i < 3 || i > 65 ???

Boolean

Java's Boolean Type - boolean

Program 6.4

Rewrite Program 6.3 so that the method sets a boolean variable, isCorrupted, to true/false and then uses that variable as the return value.

import java.io.*;
import java.util.*;

public class Payroll {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("payroll.data"));

                int numEmployees = scanner.nextInt();

                for (int i = 1; i <= numEmployees; i++) {

                        int id = scanner.nextInt();
                        String lastName = scanner.next();
                        String firstName = scanner.next();;
                        String status = scanner.next();;
                        int amount = scanner.nextInt();;

                        if (isDataCorrupt(status, amount) )
                                System.out.println("Possibly corrupt record for employee " + lastName + ", " + firstName + " (" + id + ")");
                }
        }

        public static boolean isDataCorrupt(String status, int amount) {
                boolean isCorrupted;
                if (status.equals("f") && amount < 10000 ||
                                status.equals("p") && amount > 50)
                        isCorrupted = true;
                else
                        isCorrupted = false;
                return isCorrupted;
        }
}

Program 6.5

Rewrite Program 6.4 so that the method returns the boolean expression directly.

import java.io.*;
import java.util.*;

public class Payroll {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("payroll.data"));

                int numEmployees = scanner.nextInt();

                for (int i = 1; i <= numEmployees; i++) {

                        int id = scanner.nextInt();
                        String lastName = scanner.next();
                        String firstName = scanner.next();;
                        String status = scanner.next();;
                        int amount = scanner.nextInt();;

                        if (isDataCorrupt(status, amount) )
                                System.out.println("Possibly corrupt record for employee " + lastName + ", " + firstName + " (" + id + ")");
                }
        }

        public static boolean isDataCorrupt(String status, int amount) {
                return status.equals("f") && amount < 10000 || status.equals("p") && amount > 50;
        }
}

The Conditional Operator

  • A common form of if/else is:
    if (<condition>)
    	x = <value1>
    else
    	x = <value2>
    	
    i.e., assigning different values to the same variable (x in this case) based on some condition.
    Write the expression for the absolute value of x as a conditional operator

    x >= 0 ? x : -x
    

    Write the expression for classic assignment of a letter grade based on an average

    average >= 90 ? 'A' : average >= 80 ? 'B' : average >= 70 ? 'C' : average >= 60 ? 'D' : 'F'
    

    Notes

    Files used in Lecture 6

    Lab for Lecture 6