Units 1-5 Homework
- Units 1-5 Vocabulary
- Creating a Class, describe Naming Conventions (Related to Unit 5: Writing Classes)
- Casting, specifically for Truncating or Rounding
- Accessor methods, relationship to getter (Related to Unit 5: Writing Classes)
- Concatenation, explain or illustrate rules on mixed type Concatenation
- Mutator methods, relationship to setter, describe void return type
- Compound Boolean Expression
- Static variables, Class variables, show use case in code (Relates to Unit 5: Writing Classes)
- De Morgan's Law
- Static methods, Class methods (Relates to Unit 5: Writing Classes)
- Comparing Strings
- main method, tester methods
- For Loops
- Nested loops
- Constructors
- Subclass constructor, super Keyword (This relates to Unit 5: Writing Classes)
- Overriding a method, same signature of a method
- Mutator methods, relationship to setter, describe void return type
- Public, Private, and Protected
- This
- Inheritance, Extends
- Overloading a method
- Abstract Class, Abstract Method
- Late binding of object; referencing superclass
- Polymorphism: any of overloading, overriding, late binding
- Big O notation for Hash map, Binary Search, Single loop, Nested Loop
- Units 1-5 Homework
Units 1-5 Vocabulary
Creating a Class, describe Naming Conventions (Related to Unit 5: Writing Classes)
Naming convention is lowercase first word then any words after that should be title case. A class is a set of objects that have common methods and attributes. Class is a blueprint for objects. Class has groups of variables and group of methods. To create a class use the word class and specify the access modifier.
Syntax: access_modifier class Class declarations can have modifiers, class keywords, class names, superclasses, or interfaces. An accessor method is a method that gets private data that is sotred in an object. This allows a way to get the value of each instance variable from outside of the class. Allows data use in other places than just the class that it was declared in. Accessor methods are know as getters. (Similar to how an API gets a response from a request sent from outside of the API) Mutator methods reset the value of a private variable. It gives other classes the ability to modify the value stoed in that variable without having direct access to the variable itself. Allows the user to set/mutate the value of the private variables of a class object. aka setters. Used along with getters to protect sensitive information (private) in a class. Below is an example of this A static variable (same as class variable) is a variable that is declared in the class and can only be used by objects and methods in that class. However it can be used in all instances of the class. Static variabiles can be accessed using class names and they can be accessed by static and non static methods. Only initialized once. The variable belongs to the class. Example of this use is in the math classes we worked with during trimester 1 A static method is a method that belongs to the class and not a specific object of the class. It can only access static data and not non-static data. It can call other static methods and can be accessed by the class name. It cannot refer to "this" or "super". Static methods are methods that can be called within a program without creating an object of the class Subclass inherits all the members which include fields, methods, and nested classes from its superclasss. constructors are not inheritted by the subclass. inheritance helps you create a new class out of a class that already exists. Subclasses have their own code of their own that are initialized.The invocation of a super class constructor must be the first line of the subclass constructuor Overriding is when the child class has a method that is present in the parent class. The child class must have a different implementation of the method that is already present in the parent class. depending on which method is called the result is different based on the overriden method toString(): returns a string representing the object. converts an object to a primitive value equals(): compares two strings and objects and returns true if the strings are equals and false if not hashCode(): returns an integer value generated by a hasing algorithm. it finds the hash values of given input object and returns a value that represents the hash value. hash values are used throughout code 2021 FRQ Parts a and b
a) Write the WordMatch method scoreGuess. To determine the score to be returned, scoreGuess finds the number of times that guess occurs as a substring of secret and then multiplies that number by the square of the length of guess. Occurrences of guess may overlap
within secret.
Assume that the length of guess is less than or equal to the length of secret and that guess is not an empty string. b) Write the WordMatch method findBetterGuess, which returns the better guess of its two String parameters, guess1 and guess2. If the scoreGuess method returns different values for guess1 and guess2, then the guess with the higher score is returned. If the scoreGuess method returns the same value for guess1 and guess2, then the alphabetically greater guess is returned.
The following example shows a declaration of a WordMatch object and the outcomes of some possible calls to the scoreGuess and findBetterGuess methods.
WordMatch game = new WordMatch("concatenation"); This question involves the implementation of a fitness tracking system that is represented by the StepTracker class. A StepTracker object is created with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. Write the complete StepTracker class, including the constructor and any required instance variables and
methods. Your implementation must meet all specifications and conform to the example.public class Students{
// Body of the class
}
private class studentIDs{
// Body of the Class
}
public class main
{
public static void main(String[] args) {
double myDouble = 3.14;
int myData = (int) myType;
}
}
Accessor methods, relationship to getter (Related to Unit 5: Writing Classes)public class TesterClass
{
// main method for testing
public static void main(String[] args)
{
Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
System.out.println("Name:" + s1.getName() );
System.out.println("Email:" + s1.getEmail() );
System.out.println("ID: " + s1.getId() );
}
}
/** Class Student keeps track of name, email, and id of a Student. */
class Student
{
private String name;
private String email;
private int id;
public Student(String initName, String initEmail, int initId)
{
name = initName;
email = initEmail;
id = initId;
}
// accessor methods - getters
/** getName() @return name */
public String getName()
{
return name;
}
/** getEmail() @return email */
public String getEmail()
{
return email;
}
/** getName() @return id */
public int getId()
{
return id;
}
}
TesterClass.main(null);
// You can use + to print a statement as well:
System.out.println("i am" + " a person");
// You can also combine words with integer variables
int age = 10;
System.out.println("My age is " + age);
// You can achieve all of this by simply using the Concat Method too
public String concat (String str)
Mutator methods, relationship to setter, describe void return typeimport java.util.Arrays;
public class Student {
private String name;
private Integer ID;
private String DOB;
private double GPA;
private String[] courses;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
this.ID = iD;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
this.DOB = dOB;
}
public double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
this.GPA = gPA;
}
public String[] getCourses() {
return courses;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
public static void main(String[] args) {
Student student1 = new Student();
System.out.println("Student Bio [ Before using Accessors & Mutators ]");
// calling accessor methods
System.out.print("Name: " + student1.getName());
System.out.print("\tID: " + student1.getID());
System.out.print("\tGPA: " + student1.getGPA());
System.out.print("\tDOB: " + student1.getDOB());
System.out.println("\tCourses: " + Arrays.toString(student1.getCourses()));
// calling mutator methods
student1.setName("Alex Coy");
student1.setID(3115);
student1.setGPA(2.79);
student1.setDOB("08/08/1998");
String[] courses = { "Object Oriented Programming", "Cryptography", "Photography", "Network Security" };
student1.setCourses(courses);
System.out.println("\nStudent Bio [ After using Mutators & Accessors ]");
// calling accessor methods
System.out.print("Name: " + student1.getName());
System.out.print("\tID: " + student1.getID());
System.out.print("\tGPA: " + student1.getGPA());
System.out.print("\tDOB: " + student1.getDOB());
System.out.println("\tCourses: " + Arrays.toString(student1.getCourses()));
}
}
Student.main(null);
Compound Boolean Expression
int a = 1;
int b = 2;
if (a > 0 && (b / a) == 3)
{
System.out.println("first case");
}
else
{
System.out.println("second case");
}
Static variables, Class variables, show use case in code (Relates to Unit 5: Writing Classes)public abstract class Fibo {
String name; // name or title of method
int size; // nth sequence
int hashID; // counter for hashIDs in hash map
ArrayList<Long> list; // captures current Fibonacci sequence
HashMap<Integer, Object> hash; // captures each sequence leading to final result
// Static variables being initialized once for use throughout the entire class
import java.util.Scanner;
public class deMorgan //define class
{
public static void main(String[] args) //java main method
{
int a = 0; //initializing variables
int b = 0;
System.out.println(!(a==10 || b==10)); //Will print true if a or b does not equal 10
System.out.println(a!=10 && b!=10);
}
}
deMorgan.main(null);
Static methods, Class methods (Relates to Unit 5: Writing Classes)public class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
Student.b++;
s1.showData();
}
}
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}
}
Demo.main(null);
public class Compare {
public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Practice");
// Comparing for String 1 != String 2
System.out.println("Comparing " + string1 + " and " + string2
+ " : " + string1.equals(string2));
}
}
public class Demo {
public static void main(String args[]){
System.out.print("Hello world!");
}
}
Demo.main(null);
for (int i = 0; i <= 10; i = i + 2)
{
System.out.println(i);
}
public static void main(String[] args) {
int weeks = 3;
int days = 7;
// outer loop prints weeks
for (int i = 1; i <= weeks; ++i) {
System.out.println("Week: " + i);
// inner loop prints days
for (int j = 1; j <= days; ++j) {
System.out.println(" Day: " + j);
}
}
}
public class Main {
int x;
public Main() {
x = 5;
}
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Subclass constructor, super Keyword (This relates to Unit 5: Writing Classes)public class Subclass extends Superclass {
public static void main(String args[]){
super();
}
}
Overriding a method, same signature of a methodpublic class Adult{
public void knowAge(){
System.out.println("You are an adult!");
}
}
public class Child extends Adult{
public void knowAge(){
System.out.println("You are a child!");
}
}
public class Main{
public static void main(String args[]){
Adult person = new Adult();
person.knowAge();
Child kid = new Child();
kid.knowAge();
}
}
Main.main(null);
Mutator methods, relationship to setter, describe void return type
class Example {
public void method1() {...}
private void method2() {...}
}
Inheritance, Extends
class Color extends Shade
static int plusMethodInt(int a, int b) {
return a + b;
}
static double plusMethodDouble(double a, double b) {
return a + b;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The pig says: woof woof");
}
}
class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create a Dog object
myDog.animalSound();
myDog.sleep();
}
}
Standard methods: toString(), equals(), hashCode()// Java Program for Method overloading
// By using Different Types of Arguments
// Class 1
// Helper class
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
GFG.main(null);
import java.util.Scanner;
Scanner input;
boolean separateCategory;
float currentGrade;
float desiredGrade;
float percentOfFinal;
input = new Scanner(System.in);
System.out.print("Do you want separate categories? ");
separateCategory = input.nextBoolean();
System.out.println(separateCategory);
if(separateCategory == true) {
System.out.print("Enter current grade? ");
currentGrade = input.nextInt();
System.out.println(currentGrade);
System.out.print("Enter desired grade? ");
desiredGrade = input.nextInt();
System.out.println(desiredGrade);
System.out.print("Enter percent of grade that is final? ");
percentOfFinal = input.nextFloat();
System.out.println(percentOfFinal);
input.close();
float gradeNeeded = (desiredGrade - currentGrade * (1-percentOfFinal))/percentOfFinal;
System.out.println(gradeNeeded);
}
Unit 2 - Using Objectspublic class WordMatch
{
/** The secret string. */
private String secret;
/** Constructs a WordMatch object with the given secret string of lowercase letters. */
public WordMatch(String word)
{
/* implementation not shown */
}
/** Returns a score for guess, as described in part (a).
* Precondition: 0 < guess.length() <= secret.length()
*/
public int scoreGuess(String guess)
{
int result = 0;
for (int a = 0; a < secret.length(); a++)
{
if(secret.substring(a).indexOf(guess) == 0)
{
result++;
}
}
return result * guess.length() * guess.length();
}
}
// public int scoreGuess(String guess)
// { /* to be implemented in part (a) */ }
/** Returns the better of two guesses, as determined by scoreGuess and the rules for a
* tie-breaker that are described in part (b).
* Precondition: guess1 and guess2 contain all lowercase letters.
* guess1 is not the same as guess2.
*/
public String findBetterGuess(String guess1, String guess2)
{
if(scoreGuess(guess1)>scoreGuess(guess2))
{
return guess1;
}
if(scoreGuess(guess2) > scoreGuess(guess1))
{
return guess2;
}
if(guess1.compareTo(guess2) > 0 )
{
return guess1;
}
return guess2;
}
//exercise 2
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Input a: ");
double a = input.nextDouble();
System.out.print(a);
System.out.print("Input b: ");
double b = input.nextDouble();
System.out.print(b);
System.out.print("Input c: ");
double c = input.nextDouble();
System.out.print(c);
double result = b * b - 4.0 * a * c;
if (result > 0.0) {
double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("Roots are" + r1 + " and " + r2);
} else if (result == 0.0) {
double r1 = -b / (2.0 * a);
System.out.println("Root is " + r1);
} else {
System.out.println("No real roots.");
}
//exercise 4
Scanner in = new Scanner(System.in);
System.out.print("Input: ");
double input = in.nextDouble();
System.out.print(input);
if (input > 0)
{
if (input < 1)
{
System.out.println("Positive small number");
}
else if (input > 1000000)
{
System.out.println("Positive large number");
}
else
{
System.out.println("Positive number");
}
}
else if (input < 0)
{
if (Math.abs(input) < 1)
{
System.out.println("Negative small number");
}
else if (Math.abs(input) > 1000000)
{
System.out.println("Negative large number");
}
else
{
System.out.println("Negative number");
}
}
else
{
System.out.println("Zero");
}
// exercise 6
Scanner in = new Scanner(System.in);
System.out.print("Double 1: ");
double num1 = in.nextDouble();
System.out.print(num1);
System.out.print("Double 2: ");
double num2 = in.nextDouble();
System.out.print(num2);
num1 = Math.round(num1 * 1000);
num1 = num1 / 1000;
num2 = Math.round(num2 * 1000);
num2 = num2 / 1000;
if (num1 == num2)
{
System.out.println("Same up to three decimal places");
}
else
{
System.out.println("Different");
}
// exercise 8
Scanner in = new Scanner(System.in);
System.out.print("Type a letter: ");
String input = in.next().toLowerCase();
System.out.println(input);
boolean uppercase = input.charAt(0) >= 65 && input.charAt(0) <= 90;
boolean lowercase = input.charAt(0) >= 97 && input.charAt(0) <= 122;
boolean vowels = input.equals("a") || input.equals("e") || input.equals("i")
|| input.equals("o") || input.equals("u");
if (input.length() > 1)
{
System.out.println("Error. Not a single character.");
}
else if (!(uppercase || lowercase))
{
System.out.println("Error. Not a letter. Enter uppercase or lowercase letter.");
}
else if (vowels)
{
System.out.println("Input letter is Vowel");
}
else
{
System.out.println("Input letter is Consonant");
}
// exercise 10
int i;
System.out.println ("First 10 natural numbers:");
for (i = 1;i <= 10;i++)
{
System.out.println(i);
}
System.out.println ("\n");
// part a
public static int numberOfLeapYears(int year1, int year2)
{
int numLeapYears = 0;
for (int i = year1; i <= year2; i++) {
if (isLeapYear(i)) {
numLeapYears ++;
}
}
return numLeapYears;
}
// part b
public static int dayOfWeek(int month, int day, int year)
{
int firstDay = firstDayOfYear(year);
int theDate = dayOfYear(month, day year);
int theDay = (firstDay + theDate - 1) % 7;
return theDay;
}
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) */
int numLeapYears = 0;
for (int i = year1; i <= year2; i++) {
if (isLeapYear(i)) {
numLeapYears ++;
}
}
return numLeapYears;
}
/** 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)
{
int firstDay = firstDayOfYear(year);
int theDate = dayOfYear(month, day year);
int theDay = (firstDay + theDate - 1) % 7;
return theDay;
}
// There may be instance variables, constructors, and other methods not shown.
}
public class CaesarCipher {
public static void main(String[] args) {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String message1 = "Kfzb gly!";
String message2 = "zlab zlab zlab";
String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
int shiftBy = 3 ; // showing how much to shift by
CaesarCipher caesarCipher = new CaesarCipher(); // instantiating CaesarCipher class
System.out.println("Decrypted Message1 : " + caesarCipher.decryptMessage(message1, shiftBy));
System.out.println("Decrypted Message2 : " + caesarCipher.decryptMessage(message2, shiftBy));
System.out.println("Decrypted Message3 : " + caesarCipher.decryptMessage(message3, shiftBy));
}
// method for decrypting given message by the shift int value
String decryptMessage(String input, int shiftBy){
int asciia =(int) 'a'; // assigning ascii values for a
String decryptMessage = "";
for(int i=0 ; i < input.length(); i++){
char c = input.charAt(i) ;
char newChar = c ;
// does decryption only for letters (not the exclamation mark, not spaces, etc.)
if( Character.isLetter(c) ){
int intValue = (int) c ; // finds the ascii value for given letter
int newValue = (intValue - asciia + shiftBy ) % 26 ; // assiging deciphered ascii value by subtracting the ascii value and adding the shift value
newValue = newValue + asciia ;
newChar = (char) newValue; // converting ascii value to new character
}
decryptMessage += newChar ;
}
return decryptMessage;
}
}
CaesarCipher.main(null);
Unit 5 - Writing Class
2019 Free Response Question 2The StepTracker class provides a constructor and the following methods.
public class StepTracker {
// accessing and showing our private instance variables
private int totalSteps;
private int minimumSteps;
private int daysActive;
private int days;
// constructor with the parameter
public StepTracker(int least){
minimumSteps = least;
totalSteps = 0; // values to initialize variables
daysActive = 0;
days = 0;
}
//added the dailySteps method as the "AddDailySteps"
public void AddDailySteps(int steps){
totalSteps += steps; //shows active days and the incremental counting
days++;
if (steps >= minSteps){
daysActive++; // updates the other instance variables
}
}
//the activeDays method
public int getdaysActive(){ // declared and implemented into program
return days;
}
public double avgSteps(){
if (days == 0){
return 0.0;
}
else{
//returns the calculated double of the average number of steps walked
return (double) totalSteps / days;
}
}
}