Quiz Corrections

Question 6

  • What went wrong was my though process and ideas becuase the answer the method will return false since all is assigned the value “harmchortlecrowbar” which does not contain “art”. This is the expected return value since “art” is not in any of the three individual words. This can be fixed if I checked the word and ran it properly through the algorithm where is which i meesed up and I need to work on taking each process step by step
public class Main {
    public static void main(String[] args) {
        // Method call that demonstrates the issue with the containsArt method
        boolean result = containsArt("cart", "part", "smart");
        System.out.println("Does at least one string contain 'art'? " + result);
    }

    public static boolean containsArt(String s1, String s2, String s3) {
        String all = s1 + s2 + s3;
        return (all.indexOf("art") != -1);
    }
}

Question 7

  • Here the option I chose was inccorrect as it was initialized to the incorrect variable which lead to the fact that my output would be incorrect as the inse was wrong leaving hte array to be printed in a straigh form rather with the insdie and outer loops processed propertl
public class Main {
    public static void main(String[] args) {
        for (int outer = 1; outer <= 6; outer++) {
            for (int inner = outer; inner <= 6; inner++) {
                if (inner % 2 == 0) {
                    System.out.print(inner + " ");
                }
            }
            System.out.println();
        }
    }
}

Question 9

  • A pair of number cubes is used in a game of chance. Each number cube has six sides, numbered from 1 to 6, inclusive, and there is an equal probability for each of the numbers to appear on the top side (indicating the cube’s value) when the number cube is rolled. The following incomplete statement appears in a program that computes the sum of the values produced by rolling two number cubes.

int sum = / * missing code * / ;

  • Which of the following replacements for /* missing code */ would best simulate the value produced as a result of rolling two number cubes? Responses

  • MY answer: (int) (Math.random() * 6) + (int) (Math.random() * 6)

Correct Answer: 2 + (int) (Math.random() * 6) + (int) (Math.random() * 6)

Corrections: The reason why my answer is worng is beccasuee its out of the bounds there fore it doesent met critieria and takes teh value of all even numberswithout accualy habing to processs the numbers this is becuase it doesent start at 0 and add +2 rather it adds one by on eso there is no set limit

Question 19

int x = 1;
while /* condition */ {
    if (x % 2 == 0) {
        System.out.print(x + " ");
    }
    x = x + 2;
}

The following conditions have been proposed to replace /* condition */ in the code segment.

x < 0

x <= 1

x < 10

For which of the conditions will nothing be printed?

My answerL one and two only

Correct answer: I, II, and III

  • Explanation: in my answer I overlooked option 3 because when I went throught the code becuase i bellved it gave of modular 0 there fore it could be ran through but that was not the case loop will not execute, since 1, the value of x, is not less than 0, so nothing will be printed. In condition II, the while loop will execute one time, since 1, the value of x is less than or equal to 1, however, 1 is not even, so nothing will be printed.

Question 20

/**
 * Precondition: arr.length > 0
 */
public static int mystery(int[] arr) {
    int index = 0;
    int count = 0;
    int m = -1;

    for (int outer = 0; outer < arr.length; outer++) {
        count = 0;
        for (int inner = outer + 1; inner < arr.length; inner++) {
            if (arr[outer] == arr[inner]) {
                count++;
            }
        }
        if (count > m) {
            index = outer;
            m = count;
        }
    }
    
    return index;
}

Assume that nums has been declared and initialized as an array of integer values. Which of the following best describes the value returned by the call mystery(nums) ?

  • My answer: An index of the maximum value that occurs in nums
  • Correct Answer An index of a value that occurs most often in numd

Explanation The reason why I reasilized my answer was wrong is becuas ince the algorithm is counting the number of elements that are equal to the element at the current value of outer, the index being returned could be a value in nums that is less than the maximum value.

Question 26

public class ChangeIt {
    public static void changeIt(int[] arr, int val, String word) {
        arr = new int[5];
        val = 0;
        word = word.substring(0, 5);
        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;
        }
    }

    public static void start() {
        int[] nums = { 1, 2, 3, 4, 5 };
        int value = 6;
        String name = "blackboard";
        changeIt(nums, value, name);

        for (int k = 0; k < nums.length; k++) {
            System.out.print(nums[k] + "");
        }
        System.out.println(value + "");
        System.out.println(name);
    }

    public static void main(String[] args) {
        start();
    }
}

  • What is printed as a result of the call start() ?
  • Responses
  • A
  • 0 0 0 0 0 0 black
  • B
  • 0 0 0 0 0 6 blackboard
  • C
  • 1 2 3 4 5 6 black
  • D
  • 1 2 3 4 5 0 black
  • E
  • 1 2 3 4 5 6 blackboard

  • My answer: C Correct Answer E
  • Explanation: The reason why my answer was wrong was due to the fact that the inital varable that I initalized was interpreted to be wrong as call would need to be made in method start if we wanted name to be “black” instead of “blackboard”. Assigning a new value to word in changeIt does not affect name in start Therefore the number and value should go throug blackboard but I am still not quite sure on how this is incorrect.

Question 30

if (numBoxes >= 10) {
    totalCost = numBoxes * 1.50;
} else if (numBoxes >= 5) {
    totalCost = numBoxes * 3.00;
} else if (numBoxes > 0) {
    totalCost = numBoxes * 5.00;
}

Explanation

Correct Answer B

  • Explanatio: or Segment B: This code uses else if statements, which will only execute one of the blocks of code based on the conditions. It ensures that only one condition will be met and the appropriate totalCost will be calculated. This seems to be the correct structure.

Question 32

String[][] board = new String[5][5];

// Initializing the board with "O"
for (int row = 0; row < 5; row++) {
    for (int col = 0; col < 5; col++) {
        board[row][col] = "O";
    }
}

// Manipulating the board with "X" based on a condition
for (int val = 0; val < 5; val++) {
    if (val % 2 == 1) {
        int row = val;
        int col = 0;
        while (col < 5 && row >= 0) {
            board[row][col] = "X";
            col++;
            row--;
        }
    }
}

Answer:

  • O O O O O
  • X O O O O
  • O X O O O
  • X O X O O
  • O X O X O

  • Explanatio: This code initializes a 5x5 board with “O” in each cell. It then iterates through a loop from 0 to 4, checking if the value is odd. For each odd value encountered, it initiates a sequence where “X” is placed diagonally starting from the respective row number in the first column.

Question 33

for (StudentInfo k : students) {
    if (k.getMajor().equals(theMajor)) {
        sum += k.getAge();
        count++;
    }
}

Answer

if (k.getMajor() == theMajor) {
    sum += k.getAge();
    count++;
}

EXPLANATION

  • This is correct due to the fact that the major is a String, using .equals() or .equalsIgnoreCase() methods to compare strings is recommended instead of ==, this is my mistake as I went throug the operators incorrecly and though += was equal to ++++

Question 37

public class BinarySearchExample {
    public static int binarySearch(int[] data, int target) {
        int start = 0;
        int end = data.length - 1;

        int countMidpointCalculations = 0; // Counter for midpoint calculations

        while (start <= end) {
            int mid = (start + end) / 2; // Calculate midpoint

            if (target < data[mid]) {
                end = mid - 1;
            } else if (target > data[mid]) {
                start = mid + 1;
            } else {
                return mid;
            }

            countMidpointCalculations++; // Increment the count of midpoint calculations
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] sortedArray = new int[2000]; // Assuming an array of 2000 elements

        // ... (code to fill the array with sorted elements)

        int target = 42; // Example target value
        int result = binarySearch(sortedArray, target);

        System.out.println("Result: " + result);
        System.out.println("Maximum number of midpoint calculations: " + calculateMaxMidpointCalculations(2000));
    }

    public static int calculateMaxMidpointCalculations(int arraySize) {
        return (int) (Math.log(arraySize) / Math.log(2));
    }
}

Answer and Explanation

  • my answer: 2000
  • correct answer: 11
  • Explantion: MY answer is Incorrect This is becuase it could be the number of times the loop would iterate if we were conducting a linear search. And the correct asnwer 11 works becuase t. The first iteration would check the middle element of 2000 and eliminate approximately 1000 elements. The second iteration would check the middle element of 1000 and eliminate approximately 500 elements. The third would eliminate approximately 250 elements.