Methods and Control Structures

2022 Live Review 1

Structure of a Class

//STRUCTURE OF A CLASS

//circle class
public class Circle{

    //Private instance variable w/ scope of entire class
    private double radius;

    //Constructor w/ double parameter
    public Circle (double r){
        /* implementation not shown */
    }

    /* Method signature
     * - visibility modifier (usually public)
     * - return type
     * - name
     * - parameter list (whats in the parenthesis)
     */

    //void does not return a value, just carries out task
    public void adjustSize(double factor){
        radius = radius * factor;
    }

    //return method has to include return (double)
    public double getDiameter(){
        return 2*radius;
    }

    //has to include return (double)
    public double get Circumference(){
        return 2 * radius * Math.PI;
    }
}

DailyVideo FRQ WordMatch

//2021 FRQ1 WordMatch

public 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 describe in part a
     * Precondition: 0 < guess.length <= secret.length
     */
    public int scoreGuess(String guess){
        int count = 0;
        
        //stops so that it doesn't go out of bounds
        for (int i = 0; i < (secret.length() - guess,length()); i++){
            //can also use .equals
            //compares guess to substring of secret 
            if (guess == secret.substring(i,i+guess.length)){
                count++;
            }
        }
        //returns count*guess.length^2 for score
        return count * (guess.length*guess.length);
    }

    /* Returns the better of the 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;
        }
        else if (scoreGuess(guess1) < scoreGuess(guess2)){
            return guess2;
        }
        //.compareTo is string method that tells relationship between two string with in value
        //if this returns value greater than one, this mean guess1 comes after guess2
        else if (guess1.compareTo(guess2) > 0){
            return guess1;
        }
        else {
            return guess2;
        }
    }
}

Methods and Control Structure FRQ

A: Write the getCheck method, which computes the check digit for a number according to the following rules.

Multiply the first digit by 7, the second digit (if one exists) by 6, the third digit (if one exists) by 5, and so on. The length of the method's int parameter is at most six; therefore, the last digit of a six-digit number will be multiplied by 2. Add the products calculated in the previous step. Extract the check digit, which is the rightmost digit of the sum calculated in the previous step. The following are examples of the check-digit calculation.

Example 1, where num has the value 283415:

The sum to calculate is (2x7)+(8x6)+(3x5)+(4x4)+(1x3)+(5x2)=14+48+15+16+3+10=106. The check digit is the rightmost digit of 106, or 6, and getCheck returns the integer value 6.

B: Write the isValid method. The method returns true if its parameter numWithCheckDigit, which represents a number containing a check digit, is valid, and false otherwise. The check digit is always the rightmost digit of numWithCheckDigit.

Complete method isValid below. Assume that getCheck works as specified, regardless of what you wrote in part (a). You must use getCheck appropriately to receive full credit.

public class CheckDigit
{

/** Returns the check digit for num, as described in part (a).
* Precondition: The number of digits in num is between one and six, inclusive.
* num >= 0
*/

public static int getCheck(int num){
    int multiplier = 7;
    int sum = 0;

    for (int i = 1; i <= getNumberOfDigits(num); i++){
        sum += getDigit(num, i) * multiplier;
        multiplier --;   
    }
    int check = getDigit(sum, getNumberOfDigits(sum));
    return check;
}

/** Returns true if numWithCheckDigit is valid, or false otherwise, as described in part (b).
 * Precondition: The number of digits in numWithCheckDigit is between two and seven, inclusive.
* numWithCheckDigit >= 0
 */
public static boolean isValid(int numWithCheckDigit)
{
    int num = numWithCheckDigit/10;
    int checkDigit = getCheck(num);
    
    if(getDigit(numWithCheckDigit, getNumberOfDigits(numWithCheckDigit)) == checkDigit){
        return true;
    }
    else{
        return false;
    }
}

/** Returns the number of digits in num. */
public static int getNumberOfDigits(int num)
{
    String number = String.valueOf(num);
    String[] digits = number.split("(?<=.)");  
    int length = digits.length;
    return length;
}

 

/** Returns the nth digit of num.
* Precondition: n >= 1 and n <= the number of digits in num
*/

public static int getDigit(int num, int n)
{
    String number = String.valueOf(num);
    String[] digits = number.split("(?<=.)");   
    int i = Integer.parseInt(digits[n-1]);
    return i;
}

public static void main(String[] args){
    System.out.println("Check digit of 283415: " + getCheck(283415));
    System.out.println("1592 is a valid combination of 159 and its check digit (2): " + isValid(1592));
    System.out.println("1593 is a valid combination of 159 and its check digit (3): " + isValid(1593));
}

 

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

CheckDigit.main(null);
Check digit of 283415: 6
1592 is a valid combination of 159 and its check digit (2): true
1593 is a valid combination of 159 and its check digit (3): false

Classes

Class FRQ

This question involves the implementation of the AddtionPattern class, which generates a number pattern. The AdditionPattern object is constructed with two positive integer parameters, as described below.

The first positive integer parameter indicates the starting number in the pattern. The second positive integer parameter indicates the value that is to be added to obtain each subsequent number in the pattern. The AdditionPattern class also supports the following methods.

currentNumber, which returns the current number in the pattern next, which moves to the next number in the pattern prev, which moves to the previous number in the pattern or takes no action if there is no previous number The following table illustrates the behavior of an AdditionPattern object that is instantiated by the following statement.

class AdditionPattern {
    
    private int start;
    private int step;
    private int current;

    public AdditionPattern(int start, int step){
        this.start = start;
        this.step = step;
        current = start;  
    }

    public int currentNumber(){
        return current;
    }

    public int next(){
        current = current + step;
        return current;
    }
    
    public int prev(){
         if (current > start){
            current = current - step;
            return current;
         }
         else{
            return current;
         }
    }

    public static void main(String[] args){
        AdditionPattern plus3 = new AdditionPattern(2,3);
        System.out.println("Start: " +plus3.currentNumber());
        System.out.println("Step: " + plus3.next());
        System.out.println("Current: " + plus3.currentNumber());
        System.out.println("Prev: " + plus3.prev());
    }
}

AdditionPattern.main(null);
Start: 2
Step: 5
Current: 5
Prev: 2

Arrays/ArrayLists

Arrays/ArrayLists FRQ

public class MemberInfo
{
    private String name;
    private int gradYear;
    private boolean hasGoodStanding;
    
    /** Constructs a MemberInfo object for the club member with name
    * name, graduation year gradYear, and standing hasGoodStanding.
    */

    public MemberInfo(String name, int gradYear, boolean hasGoodStanding){ 
        this.name = name;
        this.gradYear = gradYear;
        this.hasGoodStanding = hasGoodStanding;
    }
    

    /** Returns the graduation year of the club member. */
    public int getGradYear()
    {  return gradYear; }

    /** Returns true if the member is in good standing and false
    * otherwise.
    */

    public boolean inGoodStanding()
    { return hasGoodStanding; }

    // There may be instance variables, constructors, and methods
    // that are not shown.

}

public class ClubMembers
{

    private ArrayList<MemberInfo> memberList;

    /** Adds new club members to memberList, as described in part (a).
    * Precondition: names is a non-empty array.
    */

    public void addMembers(String[] names, int gradYear){ 
        for (String name: names){
            memberList.add(new MemberInfo(name, gradYear, true));
        }
    }

    /** Removes members who have graduated and returns a list of
    * members who have graduated and are in good standing,
    * as described in part (b).
    */

    public ArrayList<MemberInfo> removeMembers(int year){  
        ArrayList<MemberInfo> goodStanding = new ArrayList<MemberInfo>();	

        int i = 0;
        while(i < memberList.size()){
            if(memberList.get(i).getGradYear() <= year){
                MemberInfo removed = memberList.remove(i);
                if(removed.inGoodStanding())
                    goodStanding.add(removed);
            }
            else{
                i++;
            }
        }
                
        return goodStanding;

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

    public static void main(String[] args){
        ArrayList<MemberInfo> memberList = new ArrayList<MemberInfo>();
        memberList.add(new MemberInfo("Calissa", 2023, true));

        String[] names = new String[]{"Bria", "Sarayu", "Alice"};
        addMembers(names, 2023);
    }

}

ClubMembers.main(null);
|           addMembers(names, 2023);
non-static method addMembers(java.lang.String[],int) cannot be referenced from a static context

2D Arrays

2D Arrays FRQ

A: Write the method isNonZeroRow, which returns true if and only if all elements in row r of a two-dimensional array array2D are not equal to zero.

B: Write the method resize, which returns a new two-dimensional array containing only rows from array2D with all non-zero values. The elements in the new array should appear in the same order as the order in which they appeared in the original array.

public class ArrayResizer{

    /** Returns true if and only if every value in row r of array2D
    * is non-zero.
    * Precondition: r is a valid row index in array2D.
    * Postcondition: array2D is unchanged.
    */
    public static boolean isNonZeroRow(int[][] array2D, int r){ 
        for (int c = 0; c < array2D[0].length; c++){
            if (array2D[r][c] == 0){
                return false;
            }
        }
        return true;
    }

    /** Returns the number of rows in array2D that contain all
    * non-zero values.
    * Postcondition: array2D is unchanged.
    */

    public static int numNonZeroRows(int[][] array2D){ 
        int nonZeroRows = 0;
        for (int i = 0; i < array2D.length; i++) {
            boolean hasZero = false;
            for (int j = 0; j < array2D[i].length; j++) {
                if (array2D[i][j] == 0) {
                    hasZero = true;
                    break;
                }
            }
            if (!hasZero) {
                nonZeroRows++;
            }
        }
        return nonZeroRows;
    }


    /** Returns a new, possibly smaller, two-dimensional array that
    * contains only rows from array2D with no zeros, as described
    * in part (b).
    * Precondition: array2D contains at least one column
    * and at least one row with no zeros.
    * Postcondition: array2D is unchanged.
    */

    public static int[][] resize(int[][] array2D){ 
        int[][] newArray = new int[numNonZeroRows(array2D)][array2D[0].length];

        int newRow = 0;
        for(int oldRow = 0; oldRow < array2D.length; oldRow++){
            if(isNonZeroRow(array2D, oldRow)){
                for (int c = 0; c < array2D[0].length; c++){
                newArray[newRow] = array2D[oldRow];
            }
            newRow++;
            }
            
        }

        return newArray;
    }

    public static void main(String[] args){
        int[][] arr = {
            {2, 1, 0},
            {0, 0, 0},
            {4, 5, 6}
        };

        System.out.println(ArrayResizer.isNonZeroRow(arr, 0));
        System.out.println(ArrayResizer.isNonZeroRow(arr, 2));
        
        int[][] newArr = ArrayResizer.resize(arr);
    }

}

ArrayResizer.main(null);
false
true