Charlie FRQ Key Learnings - yajatyadav/intellijs GitHub Wiki

Unit 2

public String insertSegment(String segment, int ind){
  int IndexOF = oldSeq.indexOf(segment);
  String newSeq = oldSeq.substring(0, IndexOF) + oldSeq.substring(IndexOF + segment.length());
  System.out.println(newSeq);
  return newSeq;  
  }
  • In this FRQ, I learned about how to use indexes of previous strings to construct new strings
gradShow.display(); // part b
  • I also learned how to call objects like with the above code
LightSequence gradShow = new LightSequence("0101 0101 0101");
  • It also taught me how to construct new objects like this construction of the LightSequence object with the parameter "0101 0101 0101" being passed into it.

Unit 3

public class frq3{
  public String option1;

  public void attending(boolean rsvp){
    if(rsvp){
      System.out.println("attending");
    }
    else {
      System.out.println("not attending");
      System.exit(0);
    }
  }
  public void meal(int selection){
      if(selection == 1){
        option1 = "Thanks for attending. You will be served beef.";
      }
      else if(selection == 2){
        option1 = "Thanks for attending. You will be served chicken.";
      }
      else if(selection == 3){
        option1 = "Thanks for attending. You will be served pasta.";
      }
      else{
        option1 = "Thanks for attending. You will be served fish.";
      }
      System.out.println(option1);
    }
  }
  • In these FRQs, I practiced implementing if/else statements and conditionals.
  • I also practiced setting the variable option 1 to different strings based on the user's selection
else if(answer.equals("n")){
      rsvp = false;
      System.out.println("Sorry you can't attend.");
      }
  • I also practiced using .equals as shown above with strings to check if the strings inputted are the same.
public static void drawSquare(int x, int y, int len) {
        if(x+len>10)
            len = 10-x;
        if(y+len>10)
            len = 10-y; 
        System.out.println("side length = " + len + ", area = " + len*len);
        drawLine(x, y, x+len, y);
        drawLine(x+len,y,x+len,y-len);
        drawLine(x+len, y-len, x, y-len);
        drawLine(x, y-len, x, y);
    }
  • In the second FRQ, I practiced calling a methods inside a method to accomplish a particular task
  • I used concatenation and math operations within the print statement to correctly display side length and area.
  • I also practiced with conditionals to check if the square actually fit into the box

Unit 4

public class frq4_1{
  public static String longestStreak(String str){

    char previousChar = ' ';

    String largestStreak = "", currentStreak = "";

    for (int i = 0; i < str.length(); i++){

        if (str.charAt(i) != previousChar){

            currentStreak = "";

        }

        currentStreak += str.charAt(i);


        if (currentStreak.length() > largestStreak.length()){

            largestStreak = currentStreak;

        }

        previousChar = str.charAt(i);

        }

        return (largestStreak.charAt(0)+" "+largestStreak.length());
    } 
}
  • In this FRQ, I learned how to use a for loop with specific conditions to write an algorithm
  • I used different if statements and variables to track the longest streak of letters and retain the longest streak while traversing down the String
public class frq4_2 {
    private int startingCoins; // starting number of coins

    private int maxRounds; // maximum number of rounds played



    public frq4_2(int s, int r)

    {

        startingCoins = s;

        maxRounds = r;

    }



    /** Returns the number of coins (1, 2, or 3) that player 1 will spend.

     */

    public int getPlayer1Move(int round){
        int result = 1;

        if (round % 3 == 0){
            result = 3;
        }
        else if (round % 2 == 0){
            result = 2;
        }
        return result;
    }



    /** Returns the number of coins (1, 2, or 3) that player 2 will spend, as described in part (a).

     */

    public int getPlayer2Move(int round){
        int result = 1;

        if (round % 3 == 0){
            result = 3;
        }
        else if (round % 2 == 0){
            result = 2;
        }
        return result;
    }



    /** Plays a simulated game between two players, as described in part (b).

     */

    public void playGame() {
        int Roundnumber = 1;
        int r = 1;
        int p1coins = startingCoins;
        int p2coins = startingCoins;
        while (Roundnumber <= maxRounds && p1coins >= 3 && p2coins >= 3){
            p1coins -= getPlayer1Move(r);
            p2coins -= getPlayer2Move(r);
            if(Math.abs(getPlayer1Move(r) - getPlayer2Move(r)) == 1){
                p2coins += 1;
            }
            else if(Math.abs(getPlayer1Move(r) - getPlayer2Move(r)) == 2){
                p1coins += 2;
            }

        }
        if (p1coins > p2coins){
            System.out.println("player 1 wins");
        }
        else if (p1coins < p2coins){
            System.out.println("player 2 wins");
        }
        else{
            System.out.println("tie game");
        }

    }
}
  • In this FRQ, I learned how to use compound boolean expressions to ensure multiple criteria were met
  • While loops were also used to check that if maxrounds are reached or if any player's coins fall below 3
  • Conditionals in the loop were also used to update the player's coin values correctly

Unit 5

public class frq5_1 {
    private String hostName;

    private String address;



    public frq5_1(String n, String a)

    {

        hostName = n;

        address = a;

    }

    public String getHostName(){
        return hostName;
    }  //part 1a

    public String updateAddress(String newAddress) {  //part 1b
        String newaddress = newAddress;
        return newaddress;
    }
    public String whoInvited( String personInvited){
        String personInvited1 = personInvited;
        String greeting = "Dear " + personInvited1 + ", please attend my event at " + address + ". See you then, " + hostName;
        System.out.println(greeting);
        return greeting;
    }
}
  • In this FRQ, I learnt about the anatomy of a class, including how to use instance variables and methods
  • I created mutator methods to update the address, which would make a new address and return it.
  • I also practiced writing accessor methods and using concatenation
import java.util.Random;

public class frq5_2 {


    private static Random random = new Random();

    private String prefix;

    private static int passwordsGenerated =0;

    private int length;

    public frq5_2(int length,String prefix) {

        this.prefix = prefix;

        this.length = length;

    }

    public frq5_2(int length) {

        this.prefix = "A";

        this.length = length;

    }

    public String pwGen(){

        String pwd= this.prefix+".";

        for(int i=1;i<=this.length;i++){

            pwd+=random.nextInt(10);

        }

        passwordsGenerated+=1;

        return pwd;

    }

    public int pwCount(){
      
        return passwordsGenerated;

    }

    public static void main(String[] args) {

        frq5_2 pw1 = new frq5_2(4,"chs");
        
        System.out.println(pw1.pwGen());

        System.out.println(pw1.pwCount());

        System.out.println(pw1.pwGen());

        System.out.println(pw1.pwCount());

        frq5_2 pw2 = new frq5_2(6);

        System.out.println(pw2.pwCount());

        System.out.println(pw2.pwGen());

        System.out.println(pw2.pwCount());

        System.out.println(pw1.pwCount());

    }

}
  • In this FRQ, I again practiced loops, this time to generate different passwords
  • I also learned how to use the Math.random() function with casting and multiplication to get a custom range of random numbers
  • Finally, I learnt how to use a static variable to count how many times the class was instantiated, and therefore print the count of the passwords generated in main.

Unit 6

 public static void main(String[] args) {    
   String ing[] = {"ten","fading","post","card","thunder","hinge","trailing","batting"};    
   for (String i: ing){      
     if (i.endsWith("ing")){
      System.out.println(i);     
      }    
    }  
  }
  • In this FRQ, I learned how to use an enhanced for loop to go through an array
  • I also learned how to use the .endsWith function in a conditional to check for the end of the word
//  unit 6, question 2
// part a
public double computeBonusThreshold() {
  int total = itemsSold[0];
  int min = itemsSold[0];
  int max = itemsSold[0];
  for(int i = 1; i < itemsSold.length; i++) {
    total += itemsSold[i];
    if(itemsSold[i] < min) {
      min = itemsSold[i];
    }
    if(itemsSold[i] > max) {
      max = itemsSold[i];
    }
  }
  System.out.println((total - min - max) / (double) (itemsSold.length - 2));
  return (total - min - max) / (double) (itemsSold.length - 2);
}

// part b
public void computeWages(double fixedWage, double perItemWage) {
  double threshold = computeBonusThreshold();
  for(int i = 0; i < itemsSold.length; i++) {
    double baseWage = fixedWage + perItemWage * itemsSold[i];
    if(itemsSold[i] > threshold) {
      wages[i] = baseWage * 1.1;
    }
    else {
      wages[i] = baseWage;
    }
  }
}
  • I also wrote a method to iterate through an array and print the contents
  • I also used math operators to return a value from the method computeBonusThreshhold
  • Used a loop to find the average items sold to return that value
  • Used a for loop and conditionals to set the values in an array

Unit 7

import java.util.ArrayList;

public class frq7

{

// The list of possible user names, based on a user’s first and last names and initialized by the constructor.

private ArrayList<String> possibleNames;

 

/** Constructs a UserName object as described in part (a).

* Precondition: firstName and lastName have length greater than 0

* and contain only uppercase and lowercase letters.

*/

public frq7(String firstName, String lastName){
  for(int x = firstName.length();x >= 1;x--){
    possibleNames.add(lastName + firstName.substring(0,x));
  }
} 



 

/** Returns true if arr contains name, and false otherwise. */

public boolean isUsed(String name, String[] arr){
  for(String x: arr){
    if (name.equals(x)){
      return true;
    }
  }
  return false;
}

 

/** Removes strings from possibleNames that are found in usedNames as described in part (b).

*/

public void setAvailableUserNames(String[] usedNames){
  for(int x = 0; x < possibleNames.size(); x++){
    if (isUsed(possibleNames.get(x) , usedNames)){
      possibleNames.remove(x);
      x--;

    }
  }

}

}
  • I learned how to use a for loop to traverse an ArrayList
  • different ArrayList methods (add, remove) to check and compare specific values
  • used an enhanced for loop with String.equals()
  • learned how to manage the index to ensure that each item was check in an ArrayList if an item was deleted

Unit 8

public Plot getHighestYield(String c){

  Plot plot = null;

  int highest = this.farmPlots[0][0].getCropYield();

  for(int i=0;i<4;i++){
    for(int j=0;j<3;j++){
      if(farmPlots[i][j].getCropType().equalsIgnoreCase(c) && farmPlots[i][j].getCropYield()>highest){
        highest = farmPlots[i][j].getCropYield();
        plot = farmPlots[i][j];
         }

      }

   }

  if(plot != null){
    return plot;
  }

  else{
    return null;
  }

}
  • In this FRQ, I practiced using two for loops to traverse a 2d array
  • I learned how a 2D array is an array of arrays, and how to index row and columns using that knowledge
  • Used compound boolean expressions to check multiple conditions
  • Checked and modified values in a 2d array by using row and col indeces
public boolean sameCrop(int col){
  boolean hello = true;
  String crop = farmPlots[0][col].getCropType();
  for (int i = 0; i<4; i++){
    if(!farmPlots[i][col].getCropType().equalsIgnoreCase(crop)){
      hello = false;
      break;

    }
  }
  return hello;
}
  • Here, I wrote a method that could traverse down a specific column of a 2d array and check the values
  • practiced Boolean algebra and String methods

Unit 9

import java.util.ArrayList; class frq9pic extends frq9{ private String illustrator; public frq9pic(String t, String a, String i){ super(t, a); illustrator = i; } public void printBookInfo(){ super.printBookInfo(); System.out.println(" and illustrated by " + illustrator); } public static void main(String[] args){ ArrayList myLibrary = new ArrayList(); frq9 book1 = new frq9("Frankenstein", "Mary Shelley"); frq9 book2 = new frq9pic("The Wonderful Wizard of Oz", "L. Frank Baum", "W.W. Denslow"); myLibrary.add(book1); myLibrary.add(book2);

}
}


* In this FRQ, I practiced class inheritance
* used the extends keyword to create a child class
* created a subclass constructor that contains a reference to the super constructor to initialize the variables inherited from the parent class
* used the this keyword in the constructor
* Wrote a print method that overrrid superclass's method implementation, and called the super method inside it as well (using super keyword)
* practiced creating an ArrayList of Objects, and adding both parent and subclass objects to this arraylist, by having the declared type be different from the constructor (late binding)

``` java



// book listing class for unit 9, frq 1, part c
class frq9list{
  private frq9 book;
  private double price;
  public frq9list(frq9 book, double price){
    book = book;
    price = price;
  }
  public void printDescription(){
    book.printBookInfo();
    System.out.println(", " + price);
    }
  public static void main(String[] args){
    frq9 book1 = new frq9("Frankenstein", "Mary Shelley");
    frq9pic book2 = new frq9pic("The Wonderful Wizard of Oz", "L. Frank Baum", "W.W. Denslow");
    frq9list listing1 = new frq9list(book1, 10.99);
    listing1.printDescription();
    frq9list listing2 = new frq9list(book2, 12.99);
    listing2.printDescription();
  }
}  
  • In this part, I implemented the subclasses' methods in a new class to have different print messages be displayed, based on which printBookInfo method was called upon runtime (parent class method or subclass overridden method)

Unit 9

public class Animal {
    private String eats;
    private String species;
    private String name;

    public Animal(String e, String s, String n){
        eats = e;
        species = s;
        name = n;
    }

    public String toString(){
        return(name + " the " + species + " is a " + eats);

    }
}
  • In this part, I revised the anatomy of a class, creating a constructor and writing a method based on the instance variables
public class Herbivore extends Animal{
    public Herbivore(String species, String name){
        super("herbivore", species, name);
    }
}
  • Here, I practiced Inheritance in Java
  • Specifically, I wrote the child class constructor to call the super constructor with specific parameters unique to the child class's implementation
public class Elephant extends Herbivore{
    private int tusklength;
    public Elephant(String name, int tl){
        super("elephant", name);
        tusklength = tl;

    }

    public String toString(){
        return super.toString() + " with tusks that are " + tusklength + " meters long";
    }
}
  • Continued to practice inheritance, created a child class of a child class, and created a constructor referring to the parent class's constructor
  • also wrote a method that called on the parent class's toString method (using super keyword), which it inherited from its parent class (Animal class)

Unit 10

public class frq10 {
    public static int gcf(int a, int b){
        if(a%b == 0){
            return b;
        }
        else{
            return(gcf(b,a%b));
        }
    }

    public static String reduceFraction(int numerator, int denominator){

        if (numerator%denominator == 0){
            return (numerator + "/" + denominator + " reduces to " + numerator/denominator);
        }

        else{
            int numerator2 = numerator/gcf(numerator, denominator);
            int denominator2 = denominator/gcf(numerator, denominator);
            return (numerator + "/" + denominator + " reduces to " + numerator2 + "/" + denominator2);
        }
    }

}
  • In this unit, I practiced using recursion to create an algorithm
  • using the given math knowledge, I wrote the GCF function to find the greatest common factor between 2 numbers
  • In this function, I used if else statements, with the if containing the base case (remainder = 0) and the else containing the recursive call with new parameters
  • using the GCF function, I wrote a fraction reducing method
  • again, the if had the base case that fraction is already reduced (remainder b/w num and denom is 0) to return the original fraction
  • the else contained a call to GCF with the numerator and denominator, which would keep recursing until it found the GCF, and then use this info to reduce the fraction and then print it
⚠️ **GitHub.com Fallback** ⚠️