Methods and Control Structures

Question 1

1A

public static int getCheck(int num {    
    int sum = 0;    
    
    for (int h = 1; h <= getNumberOfDigits(num); h ++) { 
        sum += getDigit(num, h)*(8-h);    
    }    
    
    return sum % 10;}

1B

public static boolean isValid(int numWithCheckDigit) {    
    if (getCheck(numWithCheckDigit / 10) == numWithCheckDigit % 10) {    
        return true;    
    }   
    else {    
        return false;    
    }
}

Question 2

2A

public boolean simulate() {

    int position = 0;
    for (int i = 0; i < maxHops; i++) {
        int distance = hopDistance();
        
        position += distance; 

        if (position >= goalDistance) {
            return true;
        }
        else if (position < 0) {
            return false;
        }
    }
    return false; 
}

2B

public double runSimulations(int num) {    
    int count = 0;    
    
    for (int h = 0; h < num; h++) {       
        if (simulate()) {        
            count ++;        
        }    
    }    
    return (double) count / num;}

Question 3

3A

public static int factorial(int n ) {    
    if (n > 1) {    
        return n * factorial(n-1);    
    }    
    else {    
        return n;    
    }
}

3B

public static void numCombinations(int n, int r) {    
    int numWays = factorial(n) / (factorial(r) * factorial(n-4) )    

    System.out.println("There are " + numWays + " ways of choosing " + r + " items from " + n + " choices.");
}

Question 4

4A

public void updateAverage(double newVal) {    
    int newRatingTotal = count*runningAverage + newVal;    
    count++;    
    runningAverage =(double) newRatingTotal / count; 
}

4B

public int processNewRatings(int num) {    
    int invalidCount = 0;    
    for (int h = 0; h < num; h++) {        
        double temp = getNewRating();        
        if (temp >= 0.0) {            
            updateAverage(temp);        
        }            
        else {             
            invalidCount++;        
        }    
    }    
    return invalidCount;
}

Question 5

5A

public static String reverseString(String str) {    
    String result = "";    
    for (int h = str.length() - 1; h >= 0; h--) {        
        result += str.substring(h, h+1)    
    }    
    return result;
}

5B

public static void palindromeChecker(String str) {    
    String str2 = removeSpaces(str);    
    if (str2.equals(reverseString(str2))) {        
        System.out.println(str + " is a palindrome");    
    }    
    else {        
        System.out.println(str + " is not a palindrome");    
    }
}

Arrays and ArrayLists

2D Arrays

Classes