Unit 3 Boolean Expression Notes

  • Boolean expressions represent logic and tell whether something is true or false
  • Operators:
    • == (some value/equals to)
    • != (checks for inequaulity)
    • < (less than)
    • <= (less than equal to)
  • Conditional statements perform computations depending on whether a Boolean condition evaluates to true or false
  • Else-if statemnts: statement to run a condition if the orginial condition was false
  • Nested if statements are if statements within if statements
  • De Morgan's Law: !(a&&b) = (!a || !b) and !(a || b) = (!a && !b)
  • Use == to see if two object references are aliases for the same object
  • Use .equals() to see if the attributes of two objects are the same

Truth Table

  • helpful for determining outcomes when boolean values are changed
  • shows true and false outputs
  • example of simple "or" table belows

De Morgan's Law

  • Complex conditional statements can be hard to evaluate when looking at "!" or "not" operators, and comparison operators, like >, <, >=, <=, ||, &&, and more
  • De morgan's law helps by explaining how operators change when a "!" negation is present

Else Statement

  • an "Else" statement is a conditional that is evaluated if the previous "if" conditional evaluates to false. Usage below.
public class IfandElse{
    public static void main(String[] arg){
   
        int num = 50; //create a variable 
        
        if(num>50){ // check if condition is true of false (Boolean)

            System.out.println("num is greater than 18"); // print output if true
        }
        else{
            System.out.println("num is not greater than 18"); // print output when "if" evaluates to false
        }
    }
}

IfandElse.main(null);

Nested if statements - If-statements within if-statements Note - If the outer if-statement evaluates to false, the inner if-statements are not evaluated.

public class IfandElse{
    public static void main(String[] arg){
   
        int num = 20; //create a variable 
        
        if(num>30){ // check if condition is true of false (Boolean)

            System.out.println("num is greater than 18"); // print output if true
        }
        else{
            System.out.println("num is not greater than 18"); // print output when "if" evaluates to false
        }
    }
}

IfandElse.main(null);
public static boolean(int number){
    if (number % 2 ==0) {
        return true;
    }
    return false;
}
boolean cloudy = true;
boolean rainy = false;

if (!cloudy && !rainy) {
    System.out.println("Don't forget to bring a hat!")
}

2019 FRQ 1

Question 1:

The APCalendar class contains methods used to calculate information about a calendar. You will write two methods of the class

public class APCalendar
{
 /** Returns true if year is a leap year and false otherwise. */
 private static boolean isLeapYear(int year)
 { /* implementation not shown */ }

 /** Returns the number of leap years between year1 and year2, inclusive.
 * Precondition: 0 <= year1 <= year2
 */
 public static int numberOfLeapYears(int year1, int year2)
 { /* to be implemented in part (a) */ }

 /** Returns the value representing the day of the week for the first day of year,
 * where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday.
 */
 private static int firstDayOfYear(int year)
 { /* implementation not shown */ }

 /** Returns n, where month, day, and year specify the nth day of the year.
 * Returns 1 for January 1 (month = 1, day = 1) of any year.
 * Precondition: The date represented by month, day, year is a valid date.
 */
 private static int dayOfYear(int month, int day, int year)
 { /* implementation not shown */ }

 /** Returns the value representing the day of the week for the given date
 * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ...,
 * and 6 denotes Saturday.
 * Precondition: The date represented by month, day, year is a valid date.
 */
 public static int dayOfWeek(int month, int day, int year)
 { /* to be implemented in part (b) */ }

 // There may be instance variables, constructors, and other methods not shown.
}

(a) Write the static method numberOfLeapYears, which returns the number of leap years between year1 and year2, inclusive. In order to calculate this value, a helper method is provided for you.

isLeapYear(year) returns true if year is a leap year and false otherwise.

Complete method numberOfLeapYears below. You must use isLeapYear appropriately to receive full credit.

/** Returns the number of leap years between year1 and year2, inclusive.
 * Precondition: 0 <= year1 <= year2
 */
public static int numberOfLeapYears(int year1, int year2)

Q1 a) Answer:

Given Info: the parameters year1 and year 2, the isLeapYear(year) method

Return Type: return type of numberOfLeapYears is int and I have to calculate the number of leap years between 2 years and return it.

public static int numberOfLeapYears(int year1, int year2)
 {
  int count = 0;
    for (int y = year1; y <= year2; y++) {
      if (isLeapYear(y)){
        count++;
      }
  }
  return count;
 }
import java.util.Calendar;
import java.util.GregorianCalendar;

public class APCalendar
{

 /** Returns the number of leap years between year1 and year2, inclusive.
  * Precondition: 0 <= year1 <= year2
 */
 public static int numberOfLeapYears(int year1, int year2)
 {
  int count = 0;
    for (int y = year1; y <= year2; y++) {
      if (isLeapYear(y)){
        count++;
      }
  }
  return count;
 }

  /** Returns true if year is a leap year and false otherwise. */
  private static boolean isLeapYear(int year)
  {
      return new GregorianCalendar().isLeapYear(year);
  }
 
  public static void main(String[] args)
  {
      int answer = APCalendar.numberOfLeapYears(2000, 2050);
      System.out.println("Your answer should be 13: " + answer);
  }
 }

FRQ 1 Question b)

Write the static method dayOfWeek, which returns the integer value representing the day of the week for the given date (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, 2019 began on a Tuesday, and January 5 is the fifth day of 2019. As a result, January 5, 2019, fell on a Saturday, and the method call dayOfWeek(1, 5, 2019) returns 6. As another example, January 10 is the tenth day of 2019. As a result, January 10, 2019, fell on a Thursday, and the method call dayOfWeek(1, 10, 2019) returns 4. In order to calculate this value, two helper methods are provided for you

firstDayOfYear(year) returns the integer value representing the day of the week for the first day of year, where 0 denotes Sunday, 1 denotes Monday, …, and 6 denotes Saturday. For example, since 2019 began on a Tuesday, firstDayOfYear(2019) returns 2.

dayOfYear(month, day, year) returns n, where month, day, and year specify the nth day of the year. For the first day of the year, January 1 (month = 1, day = 1), the value 1 is returned. This method accounts for whether year is a leap year. For example, dayOfYear(3, 1, 2017) returns 60, since 2017 is not a leap year, while dayOfYear(3, 1, 2016) returns 61, since 2016 is a leap year.

Complete method dayOfWeek below. You must use firstDayOfYear and dayOfYear appropriately to receive full credit.

/** Returns the value representing the day of the week for the given date
 * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ...,
 * and 6 denotes Saturday.
 * Precondition: The date represented by month, day, year is a valid date.
 */
public static int dayOfWeek(int month, int day, int year)

Q1 Answer b)

public static int dayOfWeek(int month, int day, int year){
    public static int dayOfWeek(int month, int day, int year) {
        firstDay = firstDayOfYear(year); // store the day of the week of the first day
        dayAfter = dayOfYear(month, day, year); // store the number of days since new year (inclusive)
    
        return (firstDay + dayAfter - 1) % 7; // adds the day of the week to the days since new year, but minus 1 because the dayAfterNew includes the first day. then, mod 7
    }
import java.util.Calendar;
import java.util.GregorianCalendar;

public class APCalendar
{

  /** Returns the value representing the day of the week for the given date
  * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ...,
  * and 6 denotes Saturday.
  * Precondition: The date represented by month, day, year is a valid date.
  */
  public static int dayOfWeek(int month, int day, int year){
    public static int dayOfWeek(int month, int day, int year) {
        firstDay = firstDayOfYear(year); // store the day of the week of the first day
        dayAfter = dayOfYear(month, day, year); // store the number of days since new year (inclusive)
    
        return (firstDay + dayAfter - 1) % 7; // adds the day of the week to the days since new year, but minus 1 because the dayAfterNew includes the first day. then, mod 7
    }

 public static void main(String[] args)
 {
     int answer = APCalendar.dayOfWeek(1, 8, 2019);
     System.out.println("Your answer should be 2: " + answer);
 }

 /** Returns the value representing the day of the week for the first day of year,
 * where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday.
 */
 private static int firstDayOfYear(int year)
 {
     GregorianCalendar gc = new GregorianCalendar(year, Calendar.JANUARY, 1);
     return gc.get(Calendar.DAY_OF_WEEK) - 1;
 }

 /** Returns n, where month, day, and year specify the nth day of the year.
 * Returns 1 for January 1 (month = 1, day = 1) of any year.
 * Precondition: The date represented by month, day, year is a valid date.
 */
 private static int dayOfYear(int month, int day, int year)
 {
     GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
     return gc.get(Calendar.DAY_OF_YEAR);
 }
}

Conditionals Exercises

2.

import java.util.Scanner;
public class Exercise2 {

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

        System.out.println("input a: ");
        double a = input.nextDouble();
        System.out.println("Input b: ");
        double b = input.nextDouble();
        System.out.println("Input c: ");
        double c = input.nextDouble();

        double discriminant = b * b - 4 * a * c;

        if (discriminant > 0.0) {
            double root1 = (-b + Math.pow(discriminant, 0.5)/(2*a));
            double root2 = (-b - Math.pow(discriminant, 0.5)/(2*a));
            System.out.println("The roots are " + root1 + " and " + root2);
        } else if (discriminant == 0) {
            double root = (-b/(2*a));
            System.out.println("The root is " + root);
        } else {
            System.out.println("no real roots");
        }
    }
    
}

Exercise2.main(null);
input a: 
Input b: 
Input c: 
no real roots
  1. Write a Java program that reads a floating-point number and prints "zero" if the number is zero. Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000. Go to the editor
public class Exercise4 {
    


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

        System.out.print("enter number: ");
        double number = input.nextDouble();
        System.out.println(number);

        if (number > 0) {
            System.out.println("positive");
        } else if (number == 0) {
            System.out.println("zero");
        } else {
            System.out.println("negative");
        }

        if (number < 1) {
            System.out.println("negative");
        } else if (number > 1000000) {
            System.out.println("large");
        }


    }
}

Exercise4.main(null);
enter number: 3.0
positive
  1. Write a Java program that reads in two floating-point numbers and tests whether they are the same up to three decimal places. Go to the editor
public class Exercise6 {

    static double truncate(double n, int decimalPlace) {
        n = n*Math.pow(10, decimalPlace);
        n = Math.floor(n);
        n = n/Math.pow(10, decimalPlace);

        return n;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("enter number: ");
        double number1 = input.nextDouble();
        double num1Trun = truncate(number1, 3);
        System.out.println(number1);

        System.out.print("enter number: ");
        double number2 = input.nextDouble();
        double num2Trun = truncate(number2, 3);
        System.out.println(number2);

        if (num1Trun == num2Trun) {
            System.out.println("same");
        } else {
            System.out.println("diff");
        }
        input.close();

        
    }
}

Exercise6.main(null);
enter number: 3.9287655
enter number: 3.9287688
same
  1. Write a Java program that takes the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;

/**
 * Exercise6
 */
public class Exercise8 {

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

        System.out.print("enter letter: ");
        String letter = input.nextLine();
        System.out.println(letter);

        Set<String> vowels = Set.of("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");

        if(letter.length() > 1) {
            System.out.println("not one letter");
        } else if (!letter.matches("[a-zA-Z]+")) {
            System.out.println("not a letter");
        } else if (vowels.contains(letter)) {
            System.out.println("vowel");
        } else {
            System.out.println("consonant");
        }


        input.close();

        
    }
}

Exercise8.main(null);
enter letter: a
vowel
  1. Write a program in Java to display the first 10 natural numbers.
public class Exercise10 {

    
    public static void main(String[] args) {
        System.out.println("The first 10 natural numbers are:");

        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
        
    }
}

Exercise10.main(null);
The first 10 natural numbers are:
1
2
3
4
5
6
7
8
9
10
  1. Write a program in Java to input 5 numbers from keyboard and find their sum and average.
import java.util.Scanner;
import java.util.Set;

/**
 * Exercise6
 */
public class Exercise12 {

    
    public static void main(String[] args) {
        int sum = 0;
        double average;

        System.out.println("Input the 5 numbers");
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < 5; i++) {
            int num = input.nextInt();
            System.out.println(num);
            sum += num;
        }

        input.close();

        average = (double) sum/5;

        System.out.println("The sum of 5 no is: " + sum);
        System.out.println("The avg of 5 no is: " + average);
        
    }
}

Exercise12.main(null);
Input the 5 numbers
20
5
1
6
9
The sum of 5 no is: 41
The avg of 5 no is: 8.2
  1. Write a program in Java to display the multiplication table of a given integer.
public class Exercise14 {

    
    public static void main(String[] args) {
        

        System.out.println("Input the number: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();

        System.out.println("Input num of terms: ");
        int termNum = input.nextInt();

        for (int i = 0; i <= termNum; i++) {
            System.out.println(num + " X " + i + " = " + num*i);
        }

        input.close();

        
        
    }
}

Exercise14.main(null);
Input the number: 
Input num of terms: 
8 X 0 = 0
8 X 1 = 8
8 X 2 = 16
8 X 3 = 24
8 X 4 = 32
8 X 5 = 40
  1. Write a program in Java to display the pattern like right angle triangle with a number.
public class Exercise16 {

    
    public static void main(String[] args) {
        

        System.out.print("Input num of rows: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        System.out.println(num);

        

        for (int i = 1; i <= num; i++) {
            
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }

            System.out.println();
        }

        
        
    }
}

Exercise16.main(null);
Input num of rows: 5
1
12
123
1234
12345
  1. Write a program in Java to make such a pattern like right angle triangle with number increased by 1.
public class Exercise18 {

    
    public static void main(String[] args) {
        

        System.out.print("Input num of rows: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        System.out.println(num);

        int numDisplay = 1;
        

        for (int i = 1; i <= num; i++) {
            
            for (int j = 1; j <= i; j++) {
                System.out.print(numDisplay + " ");
                numDisplay++;
            }

            System.out.println();
        }

        
        
    }
}

Exercise18.main(null);
Input num of rows: 4
1 
2 3 
4 5 6 
7 8 9 10 
  1. Write a program in Java to print the Floyd's Triangle.
public class Exercise20 {

    
    public static void main(String[] args) {
        

        System.out.print("Input num of rows: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        System.out.println(num);

        int numDisplay = 1;
        

        for (int i = 1; i <= num; i++) {
            
            for (int j = 1; j <= i; j++) {
                System.out.print(numDisplay + " ");
                numDisplay++;
            }

            System.out.println();
        }

        
        
    }
}

Exercise20.main(null);
Input num of rows: 6
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21