3.1 Booleans

  • boolean expressions represent logic, find if true or false
  • operators: ==, !=, <, <=, etc

3.2 If statements

conditional statements: perform computations if boolean true or false

  • if statement: run code if true

3.3 if else

  • runs a block of code if there are alternatives

3.4 else if

  • another conditional if the frst one is false

3.5 compound boolean expressions

  • nested if: if within if (if outer is false, then inner is ignored too)
  • logical operators:

    &&:and> !!:or> !:not- short circuited evaluation

3.6 DeMorgans law

  • basically distribute the negative and reverse all the operations

These are laws named after Augustus De Morgan, a 19th C British Mathemetician. It uses the NOT operator, which takes precedent over AND and OR. It can be used to simplify expressions of true and false, and as boolean values are being compared in an if conditional, applying De Morgan's law to simplify a program's logic will be very helpful.

Overall, the idea is that: when distributing or factoring a negation from a boolean expression, the operators all switch. || changes to && and vice versa. In addition, < changes to =>, and vice versa. PunApps AP Comp Sci

In addition:

  • < becomes >=
  • > becomes <=
  • == becomes !=
  • <= becomes >
  • >= becomes <
  • != becomes ==

For example:

!(!A || !B) --> A && B

As you can see, the ! in the front propogates and distributes into the condition, negating the ! inside as well as changing the || (or) to && (and). If you plug in the values, you will see that they equate to the same thing. It may not make intuitive sense exactly, but it is a proven law.

  • can be seen in a truth table bruh - used in logic for boolean algebra, can tell what is true and false from different alignment sof the table

3.7 Comparing Objects

It might be common sense to just use the boolean equality == to compare two objects, but they will only return true if they are the same object (not a copy, but the exact memory code). If there is a variable that points to an object, it is identical, but if it is another instantiatoin of an object, it iwll be false.

String a = "Hi";
String b = "Hi";
String c = a;
String d = "Hi!";
String e = new String("Hi");
System.out.println(a == c);
System.out.println(d == b);
System.out.println(a == b); // no string constructor, so still same
System.out.println(a == e);
true
false
true
false

If you just want to commpare the two characteristics, the equals() method works.

String a = "Hi";
String b = "Hi";
String c = a;
String d = "Hi!";
String e = new String("Hi");
System.out.println(a.equals(c));
System.out.println(d.equals(b));
System.out.println(a.equals(b));
System.out.println(a.equals(e));
true
false
true
true

Although these examples are all on strings, they work on all objects.

Q1. 2019 AP CSA FRQ

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) numberOfLeapYears

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) {
    int leapYearCount = 0; // variable to keep track of amount of leap years

    // for loop: set year to year1, and while it is not yet at year2, find out if leapyear or not
    for(int year = year1; year <= year2; year++) {

        // check the year for if it is leap year
        if(isLeapYear(year)) {
            leapYearCount++; // increase count
        }
    }
    return leapYearCount; // return the integer for the count of leap years
}

The approach I took was to make a loop to go through all the years between the two years, and check if it was a leap year. If it was, it would add one to the count of the leap year. As seen above, this is that pseudocode written in actual java. Comparing to the solution code, it is almost identitcal (with the variable names as the exception).

(b) dayOfWeek

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) {
    firstDay = firstDayOfYear(year); // store the day of the week of the first day
    dayAfterNew = dayOfYear(month, day, year); // store the number of days since new year (inclusive)

    return (firstDay + dayAfterNew - 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
}

For this one, I initially began by trying to make a loop, and adding each day to the number of the firstDay day by day. I soon realized that was not the intended solution.

Instead, I set variables for the firstDay day of the week, and the days after the new year as dayAfterNew. Then, I returned the value of them added minus 1 to get some number, and modulus 7 to take the modulus (remainder). The remainder would be the day of the week, which is what is returned

Comparing to the answer, I see that the solution has the return value stored within another variable, so it is almost identitical.

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: 
The roots are -2.9384471871911697 and -7.061552812808831

4 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: 50.0
positive

6 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: 5.32532643
enter number: 5.32585
same

8 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

10 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

12 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
8
7
3
6
5
The sum of 5 no is: 29
The avg of 5 no is: 5.8

14 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: 
6 X 0 = 0
6 X 1 = 6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30

16 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: 10
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910

18 Write a program in Java to make such a pattern like right angle triangle with number increased by 1.The pattern like :

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 

20 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: 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15