2D Array #1

(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.

int[][] array2D = {{2, 1, 0},

{1, 3, 2},

{0, 0, 0},

{4, 5, 6}};

//specifically check row r
//return true if row r does not contain 0
public static boolean isNonZeroRow(int[][] array2D, int r){
//loop through row r
    for (int i=0; i<array2D[r].length; i++){
        //check element in row r equal to 0 or not
        if(array2D[r][i] == 0){
            return false;
        }
    }
    return true;
}

(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.

/** 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){ //return type is 2d array
//new 2d array storing only non zero rows
//numNonZeroRows - return # of non zero rows
//create new 2d array with length of non zero rows, loop through 2d array and check for non zero rows, add those rows to new 2d array

int[][] nonZero2dArray = new int[numNonZeroRows(array2D)][array2D[0].length]; //numNonZeroRows needs to input an 2d array and it returns an integer
int counter = 0;  //counter is for iterating through the row index in nonZero2dArray
    for(int i=0; i<array2D.length; i++) { 
        if(isNonZeroRow(array2D, i)){ //check if row i in 2dArray is non zero
            for(int c = 0, c < array2D[i].length; c++){ //we need this forloop to find the specific colume index - we can put the whole row in, we need to find the row and column index and put each element into the new 2dArray
                int column = array2D[i][c]; //create int column (primitive) because 2dArray is reference type (address) so change 2dArray won't affect new 2d array
                nonZero2dArray[counter][c] = column; 
            }
            counter++; //if isNonZeroRow returns true and we put the elements of that non zero row into the new 2d array, counter ++ -> move to the next row of new 2d array
        }

    }
    return nonZero2dArray; //return a 2d array

}

//when using method, beaware of the input parameter
//is the method static or not (are we suppose to use classObject.method())

Array & Arraylist #1

(a) Write the ClubMembers method addMembers, which takes two parameters. The first parameter is a String array containing the names of new club members to be added. The second parameter is the graduation year of all the new club members. The method adds the new members to the memberList instance variable. The names can be added in any order. All members added are initially in good standing and share the same graduation year, gradYear.

/** Constructs a MemberInfo object for the club member with name

* name, graduation year gradYear, and standing hasGoodStanding.

*/

public void addMembers(String[] names, int gradYear){
//2 parameters: string array and int gradyear
//add new memebers to memeberList -> new memeber to would be new objects adding to the list

//need to create new member object and use .add() to add them to memeberlist 

for (int i=0; i<names.length; i++) {
    MemberInfo newMember = new MemberInfo(names[i], gradYear, true);
    memberList.add(newMember);
}

}

(b) Write the ClubMembers method removeMembers, which takes the following actions.

Returns a list of all students who have graduated and are in good standing. A member has graduated if the member’s graduation year is less than or equal to the method’s year parameter. If no members meet these criteria, an empty list is returned.

Removes from memberList all members who have graduated, regardless of whether or not they are in good standing.

//return a list of good standing graduates 
//check if graduated using gradyear
//check if in goodstanding - then add to new list
//remove graduates from memberList regardless of good standing

/** 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){
    //create an arraylist
    Arraylist<MemberInfo> graduatesList= new Arraylist<MemberInfo>();

    //check if graduated using gradyear
    for(int i=memberlist.size(); i >0; i--){
        if(memberList.get(i).getGradYear() <= year){
            //check if good standing
            if (memberList.get(i).inGoodStanding())
            graduatesList.add(memberList.get(i));
        }
        //remove regardless of in good standing or not
        memberList.remove(i); 
    }
 
    return graduatesList;
}

write down all instances, methods(parameter), and getters/setters given

  • will be using them in writing code

if private instances were to be used in another class, need to use getter

can use the java quick reference sheet

(arraylist)

arraylist.size()-1 (not.length) has to loop backwards of the arraylist(dynamic) because if remove elements from arraylist index number would change so you would skip some elements

arraylist.get() array[i]

remove(i)

Arraylist graduatesList= new Arraylist();</p> </div> </div> </div>

Class #1

Methods: currentNumber - returns the current number in the pattern next - moves to the next number in the pattern prev - moves to the previous number in the pattern or takes no action if there is no previous number

Write the complete AdditonPattern class. Your implementation must meet all specifications and conform to all examples.

public class AdditionPattern{
private int start;
private int addingNum;
private int current;

//first positive integer parameter - starting number
//second positive integer parameter - value that is to be added
public AdditionPattern(int start, int addingNum){
    this.start = start;
    this.addingNum = addingNum;
    current = start;
}

public int currentNumber(){
    return current;
}

public void next(){
    current+=addingNum;
}

public void prev(){
    if(current>start){
        current-=addingNum;
    }
}
}

writing class we need

- private instances
- constructer
- methods

Methods and Control Structures #1

(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.

helper methods: getNumberOfDigits returns the number of digits in its int parameter. getDigit returns the nth digit of its int parameter.

/** 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 total = 0;

    for(int i = 1; i<=getNumberOfDigits(num); i++){
        total += getDigit(num, i) * (8 - i);
    }
    return getDigit(total, getNumberofDigit(total));

 }

(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.

//return boolean, parameter - numWithCheckDigit
/** 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 numWithoutCheckDigit = numWithCheckDigit/10;
    int checkDigit = getCheck(numWithoutCheckDigit);

    if (getDigit(numWithCheckDigit, numWithCheckDigit(total)) == checkDigit){
      return true;
    }
      return false;
 }

can initialize some values (outside/inside loop)

- int multiplier
- int total/sum

2dArray #2

getName getValue

(a) Write the mostValuableNeighbor method, which compares the item in row r and column c to the items to its left and to its right. The method determines which of the three items has the greatest value and returns its name. If more than one of the values have a value that is greatest, then any of their names can be returned. If the item has no item to its left, it is compared only to the item to its right. If the item has no item to its right, it is compared only to the item to its left.

The helper method isValid has been provided. The isValid method returns true if xPos is a valid row index and yPos is a valid column index in the two-dimensional array grid, and returns false otherwise.

Assume that the ItemGrid object ig has been created such that the two-dimensional array grid contains the following item objects.

/** Compares the item in row r and column c to the items to its

* left and to its right. Returns the name of the item with

* the greatest value, as described in part (a).

* Precondition: r and c are valid indices

*/

//getName & getValue

public String mostValuableNeighbor(int r, int c){
int maxVal = ig[r][c].getValue();
int leftVal = ig[r][c-1].getValue();
int rightVal = ig[r][c+1].getValue();

if(isValid(ig[r][c-1])){
    //if left is valid
    if(leftVal >= maxVal){
        //if greater than max
        //check if right is valid
        if (isValid(ig[r][c+1])){
            //if right is valid
            //left is greater than right
            if (leftVal >= rightVal){
                return ig[r][c-1].getName(); //return left
            }
            //if left is less then right with left greater than max
            return ig[r][c+1].getName(); //return right
        }
         //if right is not valid & left is greater than max
         return ig[r][c-1].getName();
    }
    //if left is less than max
    //check if right is valid
    if (isValid(ig[r][c+1])){
        //if right is valid
        if (rightVal >= maxVal){
            return ig[r][c+1].getName();
        }
        return ig[r][c].getName();
    }
    return ig[r][c].getName();
}
....
???????????????????!!!!!!!!!!!!!!!!!!!!!!

(b) Write the findAverage method, which returns the average value of all items in grid. For example, for the ItemGrid object ig shown in part (a), the findAverage method should return 9.5, which is the average value of the twelve items in the 2D array.

public double findAverage(){
double counter = 0;
double sum = 0;
    for(int r=0; r<ig.length; r++){
        for (int c=0; c<ig[0].length; c++) {
            sum += ig[r][c].getValue();
            counter++;
        }
    }
    return double average = sum/counter;
}

can initialize values - give it a name - easier to use

2d Array #3

(a) Write the method diagonalOp, which returns the sum of the products of the corresponding entries on the main diagonals of two given square 2D arrays that have the same dimensions. The main diagonal goes from the top-left corner to the bottom-right corner in a square 2D array.

/** Returns an integer, as described in part (a).

* Precondition: matA and matB are 2D arrays that are both square,

* have at least one row, and have the same dimensions.

*/

//return int sum of products of the diagonals of the two 2d array
public static int diagonalOp(int[][] matA, int[][] matB){
int sum = 0;
    for(int r=0; r<mat1.length; r++){
        for (int c=0; c<mat[0].length; c++){
            if (r = c){ //diagonal -> r = c
                sum += mat1[r][c] + mat2[r][c];
            }
        }
    }
    return sum;
}

(b) Write the method expandMatrix, which returns an expanded version of a given 2D array. To expand a 2D array, a new 2D array must be created and filled with values such that each element of the original 2D array occurs a total of four times in the new 2D array, arranged as shown in the example below.

returns an expanded version of a given 2D array element of the original 2D array occurs a total of four times in the new 2D array

/** Returns a 2D array, as described in part (b).

* Precondition: matA is a 2D array with at least one row and

* at least one column.

*/

//row length * 2 & column length *2
public static int[][] expandMatrix(int[][] matA){
    
}

</div>