2015 Practice Exam MCQ: 34/39

Test Corrections:

  1. Generate random value of number cubes
  • Original Answer: C. Correct Answer: E. Math.random() generates a number between 0 and 1, 1 exclusive. By multiplying Math.random() by 6 and adding 1 to it, we are able to generate a number between 1 and 6, both inclusive.
  1. showMe method with int parameter
  • Original Answer: B. Correct Answer: A. The showMe method calls itself recursively until arg is equal to 10 (It calls itself with a value that is one more than arg each iteration). The recursion ends when the method prints out "10."
  1. Loop that prints nothing
  • Original Answer: C. Correct Answer: E. In condition 1, nothing will print out since the base case is already not satisfied. In condition 2, the initialized value of x is not even so nothing will be printed. In condition 3, since x starts off as 1 and always increments by 2, nothing will be printed since x is never even.
  1. Methods start and changeIt aliases
  • Original Answer: B. Correct Answer: E. In this case, the changeIt method creates copies of the parameters, instead actually changing the values of them. Since we are referencing the original variable names, the original variable values will be printed instead of the values of the new variables.
  1. Consider the following code segment type question
  • Original Answer: A. Correct Answer: C. When the set method is called, it returns the original value that was at the index, instead of the new one. Thus, the first for loop will print out "Alex Bob Carl", as those are the original values before they are changed. The second for loop will print out "Alex Alex Alex", since it just prints out the current elements in the ArrayList students.
public class dataTypes {
    public static void main(String[] args) {
        System.out.println("Integers:");
        System.out.println("---------");
        int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
        for (int i = 0; i < intArray.length; i++) {
            System.out.print(intArray[i] + " ");
        }
        System.out.println("");
        System.out.println("");

        System.out.println("Doubles:");
        System.out.println("--------");
        int a = 10;
        int b = 7;
        System.out.println("No Casting: 10/6 = " + a/b);
        System.out.println("With Casting: 10/6 = " + (double) a/b);
        System.out.println("");
        
        System.out.println("Booleans:");
        System.out.println("---------");
        boolean c = true;
        boolean d = false;
        System.out.println(c);
        System.out.println(d);
        System.out.println(c || d);
        System.out.println(c && d);
        System.out.println(!(c && d) || (c && !d));
        System.out.println("");

        System.out.println("Characters:");
        System.out.println("-----------");
        char[] partialAlphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
        for (char alpha : partialAlphabet) {
            Character newAlpha = alpha;
            System.out.print(newAlpha + " ");
        }
        System.out.println("");
        System.out.println("");
        
        System.out.println("Strings:");
        System.out.println("--------");
        String phrase = "Hello, World!";
        System.out.println(phrase);
        phrase = phrase.substring(7, phrase.length());
        System.out.println(phrase);
        for (int j = 0; j < phrase.length(); j++) {
            System.out.print(phrase.charAt(j) + " ");
        }
    }
}

dataTypes.main(null);
Integers:
---------
1 2 3 4 5 6 7 8 

Doubles:
--------
No Casting: 10/6 = 1
With Casting: 10/6 = 1.4285714285714286

Booleans:
---------
true
false
true
false
true

Characters:
-----------
a b c d e f g 

Strings:
--------
Hello, World!
World!
W o r l d ! 

Questions


  • What are methods and control structures?
  • Methods in Java serve as functions, which when called, perform the certain actions written within its code block. Control structures are programming blocks that are used to alter the linear path that a program follows.

  • Control Structures AP FRQ
  • Look at Diverse Arrays and Matrix in Teacher code and see if you think this is Methods and Control structures.
  • Matrix.java contains a variety of methods that change the contents of a given matrix, and a variety of for loops that serve as iteration control structures, used to iterate through the contents of a matrix. DiverseArray.java contains a method that checks if an array has all distinct values, and it does so by iterating through a given array with both a conventional and enhanced for loop.

  • Look at Diverse Arrays and Matrix in Teacher code and see if you think this fits Data Types.
  • In Matrix.java, we can see a variety of data types, as there are 2-dimensional matrices that contain primitive integer type data values. The same goes for DiverseArray.java, which contains both 1-dimensional and 2-dimensional arrays that contain primitive integer data type values.

  • Describing Math.random
  • By default, Math.random returns a value between 0 and 1, 1 exclusive. Generate a random number between a minimum value and maximum value, both inclusive, write Math.random() * (max - min) + min;

  • Review DoNothingByValue, what is key knowledge here?
  • When you want to change the values of variables passed to a method, you need to make changes to them directly, instead of creating reference variables with the new values.

  • Review IntByReference, what is key knowledge here?
  • Wrapper classes can be used to turn primitive types into objects that can be called. Using wrapper classes, methods can be performed on primitive types.

  • Define "Method and Control Structures". To the Teacher, the Menu Code has the most work of methodDataTypes files that is related to the "Methods and Control Structures" topic. Such exploration would begin by asking "describe Java Methods and Control structures". Are instances of MenuRow and Runnable data types, control structures? Does Driver have control structures, enumerate them.
  • Try, catch, and runnable are all used to prevent errors from negatively affecting the program. When an error happens, the program presents a custom error message that does not take up too much space or time. Menu and Driver both contain control structures and data types, since they both integrate wrapper classes and object types, as well as use for loops and try-catch to display outputs and control the flow of the program.

  1. Users of a website are asked to provide a review of the website at the end of each visit. Each review, represented by an object of the Review class, consists of an integer indication the user's rating of the website and an optional String comment field. The comment field in a Review object ends with a period ("."), exclamation point ("!"), or letter, or is a String of length 0 if the user did not enter a comment.

    a. Write the ReviewAnalysis method getAverageRating, which returns the average rating (arithmetic mean) of all elements of allReviews.

    b. Write the ReviewAnalysis method collectComments, which collects and formats only comments that contain an exclamation point. The method returns an ArrayList of String objects containing copies of user comments from allReviews that contain an exclamation point, formatted as follows. An empty ArrayList is returned if no comment in allReviews contains an exclamation point.

    • The String inserted into the ArrayList to be returned begins with the index of Review in allReviews.
    • The index is immediately followed by a hyphen ("-").
    • The hyphen is followed by a copy of the original comment.
    • The String must end with either a period or an exclamation point. If the original comment from allReviews does not end in either a period or an exclamation point, a period is added.
// Review class for initializing individual Review objects from users
public class Review {
    private int rating;
    private String comment;

    // Review constructor for setting rating and comment values
    public Review(int r, String c) {
        rating = r;
        comment = c;
    }

    // Method for getting rating data from another class
    public int getRating() {
        return rating;
    }

    // Method for getting comment data from another class
    public String getComment() {
        return comment;
    }
}

// ReviewAnalysis class for taking all of the user reviews and making analyses about them
public class ReviewAnalysis {
    private Review[] allReviews;
    private ArrayList<String> sortedComments;

    // Constructor for initializing the allReviews array, which contains all user Review objects
    public ReviewAnalysis(Review[] reviews) {
        allReviews = reviews;
    }

    // Method for finding the average rating given by all of the users, which it does by adding all of the ratings up,
    // then dividing the sum by the number of reviews

    public double getAverageRating() {
        double averageRating = 0;
        for (Review review : allReviews) {
            averageRating += review.getRating();
        }
        averageRating /= allReviews.length;
        return averageRating;
    }

    // Method for sorting all of the comments that contain an exclamation point, which it does by iterating through the allReviews array,
    // then looping through the characters of the selected Review object's comment property, and adds the comment if it contains an exclamation point,
    // adding a period to the end of it if it does not already end with an exclamation point or period
    public ArrayList<String> collectComments() {
        sortedComments = new ArrayList<String>();
        for (int i = 0; i < allReviews.length; i++) {
            String comment = allReviews[i].getComment();
            String finalComment = "";
            for (int j = 0; j < comment.length(); j++) {
                if (comment.charAt(j) == '!') {
                    finalComment += i + "-" + comment;
                    if (comment.charAt(comment.length() - 1) != '!' && comment.charAt(comment.length() - 1) != '.') {
                        finalComment += '.';
                    }
                    break;
                }
            }
            sortedComments.add(finalComment);
        }
        
        return sortedComments;
    }
}

// Main class for presenting test cases
public class Main {
    public static void main(String[] args) {
        Review firstReview = new Review(4, "Good! Thx");
        Review secondReview = new Review(3, "OK site");
        Review thirdReview = new Review(5, "Great!");
        Review fourthReview = new Review(2, "Poor! Bad.");
        Review fifthReview = new Review(3, "");
        Review[] reviews = {firstReview, secondReview, thirdReview, fourthReview, fifthReview};
        ReviewAnalysis myObj = new ReviewAnalysis(reviews);
        System.out.println(myObj.getAverageRating());
        for (String sortedComment : myObj.collectComments()) {
            System.out.print(sortedComment + " ");
        }
    }
}

Main.main(null);
3.4
0-Good! Thx.  2-Great! 3-Poor! Bad.