CS 145 Lecture 10 – Logical operators and if

Agenda

  • logical operators: && ||
  • if statements
  • interval checking
  • clamping a value
  • getting someone’s title

Code

IntervalCheck.java

package preexam1;

public class IntervalCheck {
  public static boolean isInInterval(int lo, int hi, int givenPointX) {
    return lo <= givenPointX &&
           givenPointX <= hi;
  }

  public static void main(String[] args) {
    System.out.println(false == isInInterval(0, 10, -5));
    System.out.println(true == isInInterval(0, 10, 1));
    System.out.println(false == isInInterval(0, 10, 11));
  }
}

TitleGetter.java

package preexam1;

public class TitleGetter {

  public static int clamp(int givenPointX) {
    if (givenPointX > 100) {
      return 100;
    } else if (givenPointX < 0) {
      return 0;
    } else {
      return givenPointX;
    }
  }

  public static String getTitle(boolean isDr, boolean isMale, boolean isMarried) {
    if (isDr) {
      return "Dr.";
    } else if (isMale) {
      return "Mr.";
    } else if (!isMarried) {
      return "Miss";
    } else {
      return "Mrs.";
    }
  }

  public static void main(String[] args) {
    System.out.println(!true);
    System.out.println(!false);

    System.out.println(getTitle(false, false, false).equals("Miss"));
    System.out.println(getTitle(false, false, true).equals("Mrs."));
    System.out.println(getTitle(false, true, false).equals("Mr."));
    System.out.println(getTitle(false, true, true).equals("Mr."));

    System.out.println(getTitle(true, false, false).equals("Dr."));
    System.out.println(getTitle(true, false, true).equals("Dr."));
    System.out.println(getTitle(true, true, false).equals("Dr."));
    System.out.println(getTitle(true, true, true).equals("Dr."));
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *