AP Computer Science A

¡Supera tus tareas y exámenes ahora con Quizwiz!

Part A: class Cat

public class Cat extends Pet { public Cat (String name) { super(name); } public String speak() { return "meow"; } }

Consider the following method. public void adjust(double max, double min, double total, double n) { total = total - max - min; n = n - 2.0; System.out.println(total / n); } Consider the call adjust(25.0, 5.0, 60.0, 5.0), which appears in a method in the same class. What is printed as a result of the method call?

B. 10.0

Each of the following code segments is intended to print the word Hello. Which of the following code segments works as intended? I. System.out.print("Hello"); II. System.out.print(Hello); III. System.out.print(He); System.out.print(llo);

A. I only

In the following expression, j, k, and m are properly declared and initialized int variables. !((j == k) && (k > m)) Which of the following is equivalent to the expression above?

B. (j != k) || (k <= m)

Consider the following code segment. double d = 0.25; int i = 3; double diff = d - i; System.out.print((int)diff - 0.5); What is printed as a result of executing the code segment?

B. -2.5

The following code segment prints one or more characters based on the values of boolean variables b1 and b2. Assume that b1 and b2 have been properly declared and initialized. if (!b1 || b2) { System.out.print("A"); } else { System.out.print("B"); } if (!(b1 || b2)) { System.out.print("C"); } else { System.out.print("D"); } if (b1 && !b1) { System.out.print("E"); } If b1 and b2 are both initialized to true, what is printed when the code segment has finished executing?

C. AD

A student has created a Book class. The class contains variables to represent the following. An int variable called pages to represent the number of pages A boolean variable called isHardcover to indicate whether or not the book is hardcover The object story will be declared as type Book. Which of the following descriptions is accurate?

C. An attribute of the story object is isHardcover.

Consider the following code segment. System.out.println("W"); System.out.println("X"); System.out.print("Y"); System.out.print("Z"); What is printed as a result of executing the code segment?

D. W X YZ

Consider the following code segment. System.out.print("Hello!"); System.out.println("How "); System.out.print("are "); System.out.print("you?"); What is printed as a result of executing the code segment?

D. Hello!How are you?

Consider the following method, which returns the lesser of its two parameters. public int min(int first, int second) { /* implementation not shown */ } Assume that each of the following expressions appears in a method in the same class as the method min. Assume also that the int variables p, q, and r have been properly declared and initialized. Which of the following expressions evaluates to the minimum value among p, q, and r? I. min(min(p, q), r) II. min(p, min(q, r)) III. min(min(p, q), p)

D. I and II only

Which of the following arithmetic expressions evaluates to 1 ? I. 2 / 5 % 3 II. 2 / (5 % 3) III. 2 / 5 + 1

D. II and III only

Consider the following code segment. int x = /* initial value not shown */; int y = /* initial value not shown */; int z = x; z /= y; z += 2; Which of the following best describes the behavior of the code segment?

D. It sets z to (x / y) + 2.

Consider the following code segment. int j = 10; int k = 8; j += 2; k += j; System.out.print(j); System.out.print(" "); System.out.println(k); What is printed when the code segment is executed?

E. 12 20

Consider the following code segment. int x = 0; x++; x += 1; x = x + 1; x -= -1; System.out.println(x); What is printed when the code segment has been executed?

E. 4

Consider the following statement, which is intended to create an ArrayList named arrList to store elements only of type String. /* missing code */ = new ArrayList<String>(); Which of the following can be used to replace /* missing code */ so that the statement works as intended?

E. ArrayList<String> arrList

In the code segment below, the int variable temp represents a temperature in degrees Fahrenheit. The code segment is intended to print a string based on the value of temp. The following table shows the string that should be printed for different temperature ranges. Temperature RangeString to Print31 and below"cold"32-50"cool"51-70"moderate"​71 and above"warm" String weather; if (temp <= 31) { weather = "cold"; } else { weather = "cool"; } if (temp >= 51) { weather = "moderate"; } else { weather = "warm"; } System.out.print(weather); Which of the following test cases can be used to show that the code does NOT work as intended? I. temp = 30 II. temp = 51 III. temp = 60

A. I only

Consider the following code segment. int x = 4; int y = 6; x -= y; y += x; Which of the following best describes the behavior of the code segment?

B. Both the value of x and the value of y have been decreased.

Consider the following class. public class MagicNumber { private int num; public MagicNumber() { num = 10; } public void displayNumber() { System.out.println(num); } public void add_2() { num = num + 2; } } When located in a method in a class other than MagicNumber, which of the following code segments will compile without error? I. MagicNumber.add_2();MagicNumber.displayNumber(); II. MagicNumber n1 = new MagicNumber(); n1.add_2();n1.displayNumber(); III. n2.add_2();n2.displayNumber();

B. II only

Consider the following code segment. ArrayList<String> words = new ArrayList<String>(); words.add("mat"); words.add("new"); words.add("open"); words.add("pet"); int i = 0; while (i < words.size()) { words.remove(i); i++; } System.out.println(words.toString()); What is printed when the code segment is executed?

B. [new, pet]

Consider the following statement, which is intended to create an ArrayList named a to store only elements of type Thing. Assume that the Thing class has been properly defined and includes a no-parameter constructor. ArrayList<Thing> a = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended?

B. new ArrayList<Thing>()

In the following expression, sunny and windy are properly declared and initialized boolean variables. !sunny && !windy Which of the following is equivalent to the expression above?

C. !(sunny || windy)

Consider the following code segment. double a = 7; int b = (int) (a / 2); double c = (double) b / 2; System.out.print(b); System.out.print(" "); System.out.print(c); What is printed as a result of executing the code segment?

C. 3 1.5

Consider the following methods, which appear in the same class. public void methodA(int arg) { int num = arg * 10; methodB(num); } public void methodB(int arg) { System.out.print(arg + 10); } Consider the call methodA(4), which appears in a method in the same class. What, if anything, is printed as a result of the call methodA(4) ?

C. 50

Consider the following code segment. int quant = 20; int unitPrice = 4; int ship = 8; int total; if (quant > 10) { unitPrice = 3; } if (quant > 20) { ship = 0; } total = quant * unitPrice + ship; What is the value of total after this code segment has been executed?

C. 68

Consider the following code segment. String first = new String("duck"); String second = new String("duck"); String third = new String("goose"); if (first == second) { System.out.print("A"); } else if (second == third) { System.out.print("B"); } else if (first.equals(second)) { System.out.print("C"); } else if (second.equals(third)) { System.out.print("D"); } else { System.out.print("E"); } What is printed as a result of executing the code segment?

C. C

A teacher determines student percentages in a course as the points a student earns divided by the total points available in the grading period. Points are awarded only in whole number increments, but student percentages are to be stored as decimals. The following code segment appears in a program used to compute student percentages. Points that a student earns are stored in pointsEarned, the total points available in the grading period are stored in totalPoints, and the student percentage is stored in percentage. int pointsEarned; /* missing code */ Which of the following is most appropriate to replace /* missing code */ in the program?

C. int totalPoints; double percentage;

Consider the following code segment. boolean a = true; boolean b = true; System.out.print((b || (!a || b)) + " "); System.out.print(((!b || !a) && a) + " "); System.out.println(!(a && b) && b); What output is produced when this code segment is executed?

C. true false false

Consider the following code segment. System.out.println(hello); // Line 1 System.out.print(world); // Line 2 The code segment is intended to produce the following output but does not work as intended. hello world Which of the following changes can be made so that the code segment produces the intended output?

D. Changing print in line 2 to println

Consider the following class definition, which represents two scores using the instance variables score1 and score2. The method reset is intended to set to 0 any score that is less than threshold. The method does not work as intended. public class TestClass { private int score1; private int score2; public TestClass(int num1, int num2) { score1 = num1; score2 = num2; } public void reset(int threshold) { if (score1 < threshold) // line 14 { score1 = 0; // line 16 } else if (score2 < threshold) // line 18 { score2 = 0; } } } Which of the following changes can be made so that the reset method works as intended?

D. In line 18, change else if to if.

Consider the following definition of the class Student. public class Student { private int grade_level; private String name; private double GPA; public Student (int lvl, String nm, double gr) { grade_level = lvl; name = nm; GPA = gr; } } Which of the following object initializations will compile without error?

D. Student max = new Student (10, "Max", 3.75);

Consider the following variable declarations and initializations. int a = 2; int b = 6; int c = 3; Which of the following expressions evaluates to false ?

D. a < b != c < b

Part E: Assume that the string oldSeq has been properly declared and initialized and contains the string segment. Write a code segment that will remove the first occurrence of segment from oldSeq and store it in the string newSeq. Consider the following examples. If oldSeq is "1100000111" and segment is "11", then "00000111" should be stored in newSeq. If oldSeq is "0000011" and segment is "11", then "00000" should be stored in newSeq. If oldSeq is "1100000111" and segment is "00", then "11000111" should be stored in newSeq. Write the code segment below. Your code segment should meet all specifications and conform to the examples.

int index = oldSeq.indexOf(segment); String newSeq = oldSeq.substring(0, index) + oldSeq.substring(index + segment.length());

Consider the code segment below. int x = 10; int y = 20; System.out.print(y + x / y); What is printed as a result of executing the code segment?

D. 20

Part B: class loudDog

public class LoudDog extends Dog { public LoudDog(String name) { super(name); } public String speak() { return super.speak() + super.speak(); }

The bark method below is intended to print the string "woof" a total of num times. public static void bark(int num) { if (num > 0) { System.out.println("woof"); /* missing code */ } } Which of the following can be used to replace /* missing code */ so that the call bark(5) will cause "woof" to be printed five times?

B. bark(num - 1);

Consider the following code segment. ArrayList<Integer> myList = new ArrayList(); for (int i = 0; i < 4; i++) { myList.add(i + 1); } for (int i = 0; i < 4; i++) { if (i % 2 == 0) { System.out.print(myList.get(i) + " "); } } What output is produced as a result of executing the code segment?

D. 1 3

Consider the following code segment, which uses properly declared and initialized int variables x and y and the String variable result. String result = ""; if (x < 5) { if (y > 0) { result += "a"; } else { result += "b"; } } else if (x > 10) { if (y < 0) { result += "c"; } else if (y < 10) { result += "d"; } result += "e"; } result += "f"; What is the value of result after the code segment is executed if x has the value 15 and y has the value 5 ?

D. def

Consider the following code segment, which is intended to display 0.5. int num1 = 5; int num2 = 10; double ans = num1 / num2; System.out.print(ans); Which of the following best describes the error, if any, in the code segment?

C. The code should have cast either num1 or num2 in the expression num1 / num2 to double.

Consider the following code segment. int x; int y; x = 3; y = /* missing expression */; x = 1 + 2 * y; System.out.print(x); System.out.println(y); Which of the following can be used as a replacement for /* missing expression */ so that the code segment prints 94 ?

D. x + 1

Consider the following class. public class Purchase { private double purchase; private double tax; public Purchase(double purchaseAmt, double taxAmt) { purchase = purchaseAmt; tax = taxAmt; } public void totalAmount() { System.out.print(purchase + tax); } } Assume that a Purchase object p has been properly declared and initialized. Which of the following code segments will successfully print the total purchase amount associated with p?

E. p.totalAmount();

c.

public class BookListing { private Book myBook; private double cost; public BookListing(Book b, double c) { myBook = b; cost = c; } public void printDescription() { myBook.printBookInfo(); System.out.print(", $" + cost); } }

c.

public class Elephant extends Herbivore { private double tuskLength; public Elephant(String n, double t) { super("elephant", n); tuskLength = t; } public String toString() { return super.toString() + " with tusks " + tuskLength + " meters long"; } }

Consider the following class definitions. public class Game { private String name; public Game(String n) { name = n; } // Rest of definition not shown } public class BoardGame extends Game { public BoardGame(String n) { super(n); } // Rest of definition not shown } The following code segment appears in a class other than Game or BoardGame. Game g1 = new BoardGame("checkers"); BoardGame g2 = new Game("chess"); ArrayList<Game> My_Games = new ArrayList(); My_Games.add(g1); My_Games.add(g2); Which of the following best explains why the code segment does not compile?

B. A Game object cannot be assigned to the BoardGame reference g2.

Consider the following class definition. public class Pet { private String name; private int age; public Pet(String str, int a) { name = str; age = a; } public getName() { return name; } } Which choice correctly explains why this class definition fails to compile?

C. The accessor method is missing a return type.

The Employee class will contain a String attribute for an employee's name and a double attribute for the employee's salary. Which of the following is the most appropriate implementation of the class?

C. public class Employee { private String name; private double salary; // constructor and methods not shown }

Consider the following class definitions. public class Book { private String author; private String title; public Book(String the_author, String the_title) { author = the_author; title = the_title; } } public class Textbook extends Book { private String subject; public Textbook(String the_author, String the_title, String the_subject) { /* missing implementation */ } } Which of the following can be used to replace /* missing implementation */ so that the Textbook constructor compiles without error?

D. super(the_author, the_title); subject = the_subject;

Consider the following code segment. ArrayList<String> arrList = new ArrayList<String>(); arrList.add("A"); arrList.add("B"); arrList.add("C"); arrList.add("D"); for (int i = 0; i < arrList.size(); i++) { System.out.print(arrList.remove(i)); } What, if anything, is printed as a result of executing the code segment?

A. AC

Consider the following class definitions. public class Robot { private int servoCount; public int getServoCount() { return servoCount; } public void setServoCount(int in) { servoCount = in; } } public class Android extends Robot { private int servoCount; public Android(int initVal) { setServoCount(initVal); } public int getServoCount() { return super.getServoCount(); } public int getLocal() { return servoCount; } public void setServoCount(int in) { super.setServoCount(in); } public void setLocal(int in) { servoCount = in; } } The following code segment appears in a method in another class. int x = 10; int y = 20; /* missing code */ Which of the following code segments can be used to replace /* missing code */ so that the value 20 will be printed?

A. Android a = new Android(x); a.setServoCount(y); System.out.println(a.getServoCount());

Consider the following expression. (3 + 4 == 5) != (3 + 4 >= 5) What value, if any, does the expression evaluate to?

A. true

Consider the following code segment. boolean a = true; boolean b = false; System.out.print((a == !b) != false); What is printed as a result of executing this code segment?

B. true

Consider the following code segment. String str1 = new String("Happy"); String str2 = new String("Happy"); System.out.print(str1.equals(str2) + " "); System.out.print(str2.equals(str1) + " "); System.out.print(str1 == str2); What is printed as a result of executing the code segment?

B. true true false

Consider the following code segment. int num = 5; num *= 2; num %= 6; What is the value of num after the code segment is executed?

C. 4

The printRightToLeft method is intended to print the elements in the ArrayList words in reverse order. For example, if words contains ["jelly bean", "jukebox", "jewelry"], the method should produce the following output. jewelry jukebox jelly bean The method is shown below. public static void printRightToLeft(ArrayList<String> words) { if (words.size() > 0) { System.out.println(words.get(words.size() - 1)); /* missing code */ } } Which of the following can be used to replace /* missing code */ so that the printRightToLeft method works as intended?

C. words.remove(words.size() - 1); printRightToLeft(words);

Part D: Write a code segment that will call the insertSegment method to insert the segment "1111 1111" in the current sequence for gradShow at index 4. The resulting sequence will be stored in the string resultSeq. Write the code segment below.

String resultSeq = gradShow.insertSegment("1111 1111", 4);

Part F: Two lights will be arranged on a two-dimensional plane. The vertical distance between the two lights is stored in the double variable a. The horizontal distance between the two lights is stored in the double variable b. The straight-line distance between the two lights is given by the formula . Write a code segment that prints the straight-line distance between the two lights according to the formula above.

System.out.println(Math.sqrt(a*a + b*b));

Consider the following method. /* missing precondition */ public void someMethod(int j, int k, String oldString) { String newString = oldString.substring(j, k); System.out.println("New string: " + newString); } Which of the following is the most appropriate precondition for someMethod so that the call to substring does not throw an exception?

/* Precondition: 0 <= j <= k <= oldString.length() */

Consider the following class definition. public class Time { private int hours; private int minutes; public Time(int h, int m) { hours = h; minutes = m; } public boolean equals(Object other) { if (other == null) { return false; } Time t = (Time) other; return (hours * 60 + minutes == t.hours * 60 + t.minutes); } } The following code segment appears in a class other than Time. Time t1 = new Time(1, 10); Time t2 = new Time(0, 70); Which of the following statements will print true ? System.out.println(t1 == t2); System.out.println(t1.equals(t2)); System.out.println(equals(t1, t2);

B. II only

Consider the following class definitions. public class Road { private String roadName; public Road(String name) { roadName = name; } } public class Highway extends Road { private int speedLimit; public Highway(String name, int limit) { super(name); speedLimit = limit; } } The following code segment appears in a method in another class. Road r1 = new Highway("Interstate 101", 55); // line 1 Road r2 = new Road("Elm Street"); // line 2 Highway r3 = new Road("Sullivan Street"); // line 3 Highway r4 = new Highway("New Jersey Turnpike", 65); // line 4 Which of the following best explains the error, if any, in the code segment?

C. Line 3 will cause an error because a Highway variable cannot be instantiated as an object of type Road.

Consider the following method. public void printSomething (int num, boolean val) { num--; System.out.print(val); System.out.print(num); } Consider the following code segment, which appears in a method in the same class as printSomething. printSomething(1, true); printSomething(2, true); What is printed as a result of executing the code segment?

C. true0true1

Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is intended to print the sum of the greatest two of the three values but does not work in some cases. if (a > b && b > c) { low = c; } if (a > b && c > b) { low = b; } else { low = a; } System.out.println(a + b + c - low); For which of the following values of a, b, and c does the code segment NOT print the correct value?

E. a = 3, b = 2, c = 1

(b) Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of all available mechanics. If there is no available mechanic, an empty list is returned. A mechanic is available if the mechanic's identifier does not appear in schedule. Suppose schedule has the following contents. For these contents of schedule, availableMechanic should return an ArrayList containing the values 2, 3, 4, and 5 (in any order). Complete the availableMechanics method. Assume that addRepair works as specified, regardless of what you wrote in part (a). /** Returns an ArrayList containing the mechanic identifiers of all available mechanics, * as described in part (b). */ public ArrayList<Integer> availableMechanics()

public ArrayList<Integer> availableMechanics() { ArrayList<Integer> availableList = new ArrayList<Integer>(); for(int i = 0; i < numberOfMechanics; i++) { int count = 0; for(CarRepair c : schedule) { if(c.getMechanicNum() = i) { count++; } } if(count == 0) { availableList.add(i); } } return availableList; }

Consider the following class that represents the test results of a group of students that took a multiple-choice test. Write the TestResults method highestScoringStudent, which returns the name of the student who received the highest score on the test represented by the parameter key. If there is more than one student with the highest score, the name of any one of these highest-scoring students may be returned. You may assume that the size of each answer sheet represented in the ArrayList sheets is equal to the size of the ArrayList key. In writing highestScoringStudent, assume that getScore works as specified, regardless of what you wrote in part (a). Complete method highestScoringStudent below

public String highestScoringStudent(ArrayList<String> key) { StudentAnswerSheet highestScorer = sheets.get(0); for(StudentAnswerSheet sheet : sheets) { if(sheet.getScore(key) > highestScorer.getScore(key)) { highestScorer = sheet; } } return highestScorer.getName();}

(a) Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the bay with identifier b. The repair can be scheduled if mechanic m and bay b are both available. A mechanic is available if the given mechanic number does not appear in an element of schedule and a bay is available if the given bay number does not appear in an element of schedule. If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true. If either the mechanic or the bay are not available, the addRepair method returns false. The following sequence of statements provides examples of the behavior of the addRepair method. The statement RepairSchedule r = new RepairSchedule(6); constructs a new RepairSchedule object r. No repairs have been scheduled. Mechanics are numbered 0 through 5. The call r.addRepair(3, 4) returns true because neither mechanic 3 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 1) returns true because neither mechanic 0 nor bay 1 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 2) returns false because mechanic 0 is present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(2, 4) returns false because bay 4 is present in schedule. The contents of schedule after the call are as follows. The call r.carOut(4) removes the repair in bay 4 from schedule. The carOut method is shown here to illustrate that bays and mechanics become available when car repairs are complete. You do not need to write or call this method. The contents of schedule after the call are as follows. The call r.addRepair(1, 4) returns true because neither mechanic 1 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. Complete the addRepair method. /** Attempts to schedule a repair by a given mechanic in a given bay as described in part (a). * Precondition: 0 <= m < numberOfMechanics and b >= 0 */ public boolean addRepair(int m, int b)

public boolean addRepair (int m, int b) { for(CarRepair c : schedule) { if(c.getMechanicNum() == m) || c.getBayNum == b) { return false; } } schedule.add(new CarRepair(m, b)); return true; }

Write the StudentAnswerSheet method getScore. The parameter passed to method getScore is an ArrayList of strings representing the correct answer key for the test being scored. The method computes and returns a double that represents the score for the student's test answers when compared with the answer key. One point is awarded for each correct answer and ¼ of a point is deducted for each incorrect answer. Omitted answers (indicated by "?") do not change the student's score. Complete method getScore below.

public double getScore(ArrayList<String> key) { double score = 0; for(int i = 0; i < answers.size(); i++) { if(answers.get(i).equals(key.get(i))) { score+=1; } else if(!answers.get(i).equals("?")) { score -= 0.25; } } return score; }

In the code segment below, myList is an ArrayList of integers. The code segment is intended to remove all elements with the value 0 from myList. int j = 0; while (j < myList.size()) { if (myList.get(j) == 0) { myList.remove(j); } j++; } The code segment does not always work as intended. For which of the following lists does the code segment NOT produce the correct result?

C. {1, 0, 0, 2}

Part B: StudentAdvance

public class StudentAdvance extends Advance { public StudentAdvance(int days) { super(days); } public double getPrice() { return super.getPrice()/2; } public String toString() { return super.toString() + " Student ID Required"; } }

A teacher has created a Student class. The class contains the following. An int variable called grade to represent the student's grade level A String variable called name to represent the student's name A double variable called average to represent the student's grade point average A method called updateAverage that updates the student's average. The object greg will be declared as type Student. Which of the following descriptions is accurate?

A. greg is an instance of the Student class.

Consider the following code segment. System.out.print("cat "); System.out.println("dog "); System.out.println("horse "); System.out.print("cow "); What is printed as a result of executing the code segment?

B. cat dog horse cow

Consider the following class definition. The method appendIt is intended to take the string passed as a parameter and append it to the instance variable str. For example, if str contains "week", the call appendIt("end") should set str to "weekend". The method does not work as intended. public Class StringThing { private String str; public StringThing(String myStr) { str = myStr; } public void appendIt(String s) // line 10 { str + s; // line 12 } } Which of the following changes should be made so that the appendIt method works as intended?

C. Line 12 should be changed to str = str + s;

Consider the following code segment, which is intended to calculate the average of two quiz scores. double avg = 15 + 20; avg /= 2; Which of the following best describes the behavior of the code segment?

C. The code segment stores 17.5 in avg because 17.5 is the result of the floating point division of 35.0 by 2.

2a.

public double computeBonusThreshold() { int total = itemsSold[0]; int min = itemsSold[0]; int max = itemsSold[0]; for(int i = 1; i < itemsSold.length; i++) { total += itemsSold[i]; if(itemsSold[i] < min) { min = itemsSold[i]; } if(itemsSold[i] > max) { max = itemsSold[i]; } } return (total - min - max) / (double)(itemsSold.length-2); }

2b.

public void computeWages(double fixedWage, double perItemWage) { double threshold = computeBonusThreshold(); for(int i = 0; i < itemsSold.length; i++) { double baseWage = fixedWage + perItemWage * itemsSold[i]; if(itemsSold[i] > threshold) { wages[i] = baseWage * 1.1; } else { wages[i] = baseWage; } } }

Question 2 part A: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. Employees at a store are paid daily wages according to the following rules. Each employee is paid the same fixed amount per day. Each employee is paid an additional amount for each item they sold on that day. Daily Bonus:If the number of items sold that day by an employee is greater than a computed threshold, then the employee also receives a bonus equal to 1010 percent of the employee's daily wages. You will write two methods in the Payroll class below. public class Payroll { private int[] itemsSold; // number of items sold by each employee private double[] wages; // wages to be computed in part (b) /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() { /* To be implemented in part (a) */ } /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage) { /* To be implemented in part (b) */ } // Other instance variables, constructors, and methods not shown. } The bonus threshold is calculated based on the number of items sold by all employees on a given day. The employee with the greatest number of sales and the employee with the least number of sales on that day are ignored in the calculation. The average number of items sold by the remaining employees on that day is computed, and this value is used as the bonus threshold. For a given day, the number of items sold by each employee is stored in the array itemsSold. The example below shows the contents of itemsSold for a day in which there were ten employees. Each array index represents an individual employee. For example, itemsSold[3] represents the number of items sold by employee 3. Based on the information in the table, the bonus threshold is calculated as follows. (48+50+37+62+38+70+55+37+64+60)−37−708=51.75(48+50+37+62+38+70+55+37+64+60)−37−708=51.75 (a) Complete the method computeBonusThreshold below, which is intended to return the bonus threshold based on the contents of the itemsSold array. Assume that itemsSold has been filled appropriately, and that the array contains at least three employees. /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() The computeWages method is intended to calculate the wages for each employee and to assign them to the appropriate element of the array wages. For example, wages[3] should be assigned the wages for employee33. An employee's wages consist of their daily wages plus a possible bonus and are calculated as follows. Each employee's wages are equal to the fixed wage plus the number of items sold times the amount paid per item sold. If the employee sold more items than the bonus threshold, the employee also receives a 1010 percent bonus added to their wages. As described in part (a), computeBonusThreshold() returns 51.75 for the example array below. Suppose that fixedWage is 10.0 and perItemWage is 1.5. Employee 00 did not sell more items than the bonus threshold, so employee 00's wages are equal to 10.0 + 1.5 * 48, which evaluates to 82.0. This value will be assigned to wages[0]. Employee 99 sold more items than the bonus threshold, so employee 99 receives a 1010 percent bonus. Employee 99's wages are equal to (10.0 + 1.5 * 60) * 1.1, or 110.0. This value will be assigned to wages[9]. (b) Write the method computeWages. Assume that itemsSold has been filled appropriately, and there are at least three employees in the array. Assume also that the wages array and the itemsSold array have the same length. Your solution must call computeBonusThreshold appropriately to receive full credit. /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage)

public double computeBonusThreshold() { int total = itemsSold[0]; int min = itemsSold[0]; int max = itemsSold[0]; for(int i = 1; i < itemsSold.length; i++) { total += itemsSold[i]; if(itemsSold[i] < min) { min = itemsSold[i]; } if(itemsSold[i] > max) { max = itemsSold[i]; } } return (total - min - max) / (double) (itemsSold.length - 2); }

Question 2 part B: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. Employees at a store are paid daily wages according to the following rules. Each employee is paid the same fixed amount per day. Each employee is paid an additional amount for each item they sold on that day. Daily Bonus:If the number of items sold that day by an employee is greater than a computed threshold, then the employee also receives a bonus equal to 1010 percent of the employee's daily wages. You will write two methods in the Payroll class below. public class Payroll { private int[] itemsSold; // number of items sold by each employee private double[] wages; // wages to be computed in part (b) /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() { /* To be implemented in part (a) */ } /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage) { /* To be implemented in part (b) */ } // Other instance variables, constructors, and methods not shown. } The bonus threshold is calculated based on the number of items sold by all employees on a given day. The employee with the greatest number of sales and the employee with the least number of sales on that day are ignored in the calculation. The average number of items sold by the remaining employees on that day is computed, and this value is used as the bonus threshold. For a given day, the number of items sold by each employee is stored in the array itemsSold. The example below shows the contents of itemsSold for a day in which there were ten employees. Each array index represents an individual employee. For example, itemsSold[3] represents the number of items sold by employee 3. Based on the information in the table, the bonus threshold is calculated as follows. (48+50+37+62+38+70+55+37+64+60)−37−708=51.75(48+50+37+62+38+70+55+37+64+60)−37−708=51.75 (a) Complete the method computeBonusThreshold below, which is intended to return the bonus threshold based on the contents of the itemsSold array. Assume that itemsSold has been filled appropriately, and that the array contains at least three employees. /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() The computeWages method is intended to calculate the wages for each employee and to assign them to the appropriate element of the array wages. For example, wages[3] should be assigned the wages for employee33. An employee's wages consist of their daily wages plus a possible bonus and are calculated as follows. Each employee's wages are equal to the fixed wage plus the number of items sold times the amount paid per item sold. If the employee sold more items than the bonus threshold, the employee also receives a 1010 percent bonus added to their wages. As described in part (a), computeBonusThreshold() returns 51.75 for the example array below. Suppose that fixedWage is 10.0 and perItemWage is 1.5. Employee 00 did not sell more items than the bonus threshold, so employee 00's wages are equal to 10.0 + 1.5 * 48, which evaluates to 82.0. This value will be assigned to wages[0]. Employee 99 sold more items than the bonus threshold, so employee 99 receives a 1010 percent bonus. Employee 99's wages are equal to (10.0 + 1.5 * 60) * 1.1, or 110.0. This value will be assigned to wages[9]. (b) Write the method computeWages. Assume that itemsSold has been filled appropriately, and there are at least three employees in the array. Assume also that the wages array and the itemsSold array have the same length. Your solution must call computeBonusThreshold appropriately to receive full credit. /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage)

public void computeWages(double fixedWage, double perItemWage) { double threshold = computeBonusThreshold(); for(int i = 0; i < itemsSold.length; i++) { double baseWage = fixedWage + perItemWage * itemsSold[i]; if(itemsSold[i] > threshold) { wages[i] = baseWage * 1.1; } else { wages[i] = baseWage; } } }

The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5. /* missing precondition */ public static int addItUp(int m, int n) { int sum = 0; for (int j = m; j <= n; j++) { sum += j; } return sum; } Which of the following is the most appropriate precondition for the method?

A. /* Precondition: m <= n */

Consider the following class declarations. public class Hat { private String size; public Hat(String s) { size = s; } public String toString() { return "Size " + size + " hat"; } } public class BallCap extends Hat { private String team; public BallCap(String mySize, String myTeam) { super(mySize); team = myTeam; } public String toString() { return super.toString() + " with " + team + " logo"; } } A code segment located in a different class is intended to produce the following output. Size L hat with Denver logo Which of the following code segments will produce this output?

A. BallCap myHat = new BallCap("L", "Denver"); System.out.println(myHat);

Consider the class definition below. The method levelUp is intended to increase a Superhero object's strength attribute by the parameter amount. The method does not work as intended. public class Superhero { private String name; private String secretIdentity; private int strength; public Superhero(String realName, String codeName) { name = realName; secretIdentity = codeName; strength = 5; } public int levelUp(int amount) // line 14 { strength += amount; // line 16 } } Which of the following changes should be made so that the levelUp method works as intended?

A. In line 14, levelUp should be declared as type void.

Consider the following class definition. public class Document { private int pageCount; private int chapterCount; public Document(int p, int c) { pageCount = p; chapterCount = c; } public String toString() { return pageCount + " " + chapterCount; } } The following code segment, which is intended to print the page and chapter counts of a Document object, appears in a class other than Document. Document d = new Document(245, 16); System.out.println( /* missing code */ ); Which of the following can be used as a replacement for /* missing code */ so the code segment works as intended?

A. d.toString()

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following code segment appears in a method in the same class as bSearch. int[] nums = {0, 4, 4, 5, 6, 7}; int result = bSearch(nums, 0, nums.length - 1, 4); What is the value of result after the code segment has been executed?

B. 2

Consider the following class definitions. public class Aclass { public void methodX() { System.out.print("Super X "); methodY(); } public void methodY() { System.out.print("Super Y "); methodZ(); } public void methodZ() ( System.out.print("Super Z"); } } public class Bclass extends Aclass { public void methodX() { super.methodX(); } public void methodY() { System.out.print("Sub Y "); methodZ(); } } The following code segment appears in a class other than Aclass or Bclass. Aclass thing = new Bclass(); thing.methodX(); The code segment is intended to display the following. Super X Super Y Super Z Which of the following best explains why the code segment does not work as intended?

B. The variable thing should be instantiated as an Aclass object because methodY is overridden in Bclass.

Consider the following code segment. ArrayList<String> syllables = new ArrayList<String>(); syllables.add("LA"); syllables.add(0, "DI"); syllables.set(1, "TU"); syllables.add("DA"); syllables.add(2, syllables.get(0)); syllables.remove(1); System.out.println(syllables.toString()); What is printed as a result of executing the code segment?

B. [DI, DI, DA]

Consider the following correct implementation of the selection sort algorithm. public static void selectionSort(int[] elements) { for (int j = 0; j < elements.length - 1; j++) { int minIndex = j; for (int k = j + 1; k < elements.length; k++) { if (elements[k] < elements[minIndex]) { minIndex = k; } } if (j != minIndex) { int temp = elements[j]; elements[j] = elements[minIndex]; elements[minIndex] = temp; // line 19 } } } The following declaration and method call appear in a method in the same class as selectionSort. int[] arr = {30, 40, 10, 50, 20}; selectionSort(arr); How many times is the statement elements[minIndex] = temp; in line 19 of the method executed as a result of the call to selectionSort ?

C. 3

In the code segment below, assume that the ArrayList object numbers has been properly declared and initialized to contain [0, 2, 4, 5]. for (int k = numbers.size() - 1; k >= 0; k--) { if (numbers.get(k) > k) { System.out.print(k + " "); } } What, if anything, is printed as a result of executing the code segment?

C. 3 2 1

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; } elements[possibleIndex] = temp; // line 12 } } The following declaration and method call appear in a method in the same class as insertionSort. int[] nums = {8, 7, 5, 4, 2, 1}; insertionSort(nums); How many times is the statement elements[possibleIndex] = temp; in line 12 of the method executed as a result of the call to insertionSort ?

C. 5

Consider the following class definitions. public class Thing { /* implementation not shown */ } public class MoreThing extends Thing { /* implementation not shown */ } The following code segment appears in a class other than Thing or MoreThing. Thing[] arr = new MoreThing[3]; // line 1 Thing t1 = new Thing(); Thing t2 = new MoreThing(); // line 3 MoreThing t3 = new MoreThing(); arr[0] = t1; // line 5 arr[1] = t2; // line 6 arr[2] = t3; // line 7 Which of the following best explains the error in the code segment?

C. Line 5 will cause an error because the types of arr[0] and t1 are different.

Consider the following class definitions. public class Drink { // implementation not shown } public class Coffee extends Drink { // There may be instance variables and constructors that are not shown. // No methods are defined for this class. } The following code segment appears in a method in a class other than Drink or Coffee. Coffee myCup = new Coffee(); myCup.setSize("large"); Which of the following must be true so that the code segment will compile without error?

C. The Drink class must have a public method named setSize that takes a String value as its parameter.

In the following code segment, assume that the ArrayList wordList has been initialized to contain the String values ["apple", "banana", "coconut", "lemon", "orange", "pear"]. int count = 0; for (String word : wordList) { if (word.indexOf("a") >= 0) { count++; } } System.out.println(count); What is printed as a result of executing the code segment?

D. 4

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; // line 10 } elements[possibleIndex] = temp; } } The following declaration and method call appear in a method in the same class as insertionSort. int[] arr = {10, 8, 3, 4}; insertionSort(arr); How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ? 0

D. 5

Consider the following classes. public class Base { public Base() { System.out.print("Base" + " "); } } public class Derived extends Base { public Derived() { System.out.print("Derived" + " "); } } Assume that the following statement appears in another class. Derived d1 = new Derived(); What is printed as a result of executing the statement?

D. Base Derived

Consider the following class declarations. public class Parent { public void first() { System.out.print("P"); second(); } public void second() { System.out.print("Q"); } } public class Child extends Parent { public void first() { super.first(); } public void second() { super.second(); System.out.print("R"); } } public class Grandchild extends Child { public void first() { super.first(); System.out.print("S"); } public void second() { super.second(); System.out.print("T"); } } Which of the following code segments, if located in another class, will produce the output "PQRTS" ?

D. Grandchild d = new Grandchild(); d.first();

Consider the following declaration for a class that will be used to represent points in the xy-coordinate plane. public class Point { private int x; //x-coordinate of the point private int y; //y-coordinate of the point public Point() { x = 0; y = 0; } public Point(int a, int b) { x = a; y = b; } //Other methods not shown } The following incomplete class declaration is intended to extend the above class so that points can be named. public class NamedPoint extends Point { private String name; // name of point //Constructors go here // Other methods not shown } Consider the following proposed constructors for this class. I. public NamedPoint() { name = ""; } II. public NamedPoint(int d1, int d2, String pointName) { x = d1; y = d2; name = pointName; } III. public NamedPoint(int d1, int d2, String pointName) { super(d1, d2); name = pointName; } Which of these constructors would be legal for the NamedPoint class?

D. I and III only

The removeElement method is intended to remove all instances of target from the ArrayList object data passed as a parameter. The method does not work as intended for all inputs. public void removeElement(ArrayList<Integer> data, int target) { for (int j = 0; j < data.size(); j++) { if (data.get(j).equals(target)) { data.remove(j); } } } Assume that the ArrayList object scores and the int variable low_score have been properly declared and initialized. In which of the following cases will the method call removeElement(scores, low_score) fail to produce the intended result?

D. When scores is [8, 8, 4, 3, 3, 6] and low_score is 3

Consider the following code segment. ArrayList<Integer> nums = new ArrayList<>(); nums.add(3); nums.add(2); nums.add(1); nums.add(0); nums.add(0, 4); nums.set(3, 2); nums.remove(3); nums.add(2, 0); Which of the following represents the contents of nums after the code segment has been executed?

D. [4, 3, 0, 2, 0]

Consider the following two classes. public class Dog { public void act() { System.out.print("run "); eat(); } public void eat() { System.out.print("eat "); } } public class UnderDog extends Dog { public void act() { super.act(); System.out.print("sleep "); } public void eat() { super.eat(); System.out.print("bark "); } } Assume that the following declaration appears in a class other than Dog.Dog fido = new UnderDog ( ) ;What is printed as a result of the call fido.act() ?

D. run eat bark sleep

In the following code segment, assume that the ArrayList numList has been properly declared and initialized to contain the Integer values [1, 2, 2, 3]. The code segment is intended to insert the Integer value val in numList so that numList will remain in ascending order. The code segment does not work as intended in all cases. int index = 0; while (val > numList.get(index)) { index++; } numList.add(index, val); For which of the following values of val will the code segment not work as intended?

E. 4

Part C: Write a statement that will be used to update the gradShow light sequence to "0011 0011 0011". Write the statement below.

gradShow.changeSequence("0011 0011 0011");

(c) The programmer would like to add a method called getAllGroupAssignments that returns a list of assignments that have been designated as having parts where students worked in groups. A group assignment can appear in any category. Write a description of how you would change the Assignment and StudentAssignments classes in order to support this modification. Make sure to include the following in your response. Write the method header for the getAllGroupAssignments method. Identify any new or modified variables, constructors, or methods aside from the getAllGroupAssignments method. Do not write the program code for this change. Describe, for each new or revised variable, constructor, or method, how it would change or be implemented, including visibility and type. You do not need to describe the getAllGroupAssignments method. Do not write the program code for this change.

public ArrayList<Assignment> getAllGroupAssignments() The Assignment class would have to be changed to have a private boolean value inGroup which returns either true or false depending on if students worked in groups. The Assignment class should also include a public getGroups() method which returns the groups the students worked in. The StudentAssignments class should include the getAllGroupAssignments() method because it has an array list of Assignment objects which can be iterated through.

Part A: Advance

public class Advance extends Ticket { private int dia; public Advance(int days) { super(); dia = days; } public double getPrice() { if(dia >= 10) { return 30.0; } else { return 40.0; } } }

a.

public class Animal { private String classification; private String species; private String name; public Animal(String c, String s, String n) { classification = c; species = s; name = n; } public String toString() { String str = ""; str = name + " the " + species + " is a " + classification; return str; } }

b.

public class Herbivore extends Animal { public Herbivore(String s, String n) { super("herbivore", s, n); } }

(a) Write the StudentAssignments method getNumberOfAs. The method returns the number of assignments in a given category that have a grade greater than or equal to 90. Complete method getNumberOfAs. /** Returns the number of assignments in a given category that have a grade greater than or * equal to 9090, as described in part (a) */ public int getNumberOfAs(String cat)

public int getNumberOfAs(String cat) { int count = 0; for(Assignment a : assignmentList) { if(a.getGrade() >= 90 && a.getCategory().equals(cat)) { count++; } } return count; }

Part C: Kennel - allSpeak

public void allSpeak() { for(int i = 0; i < petList.size(); i++) { System.out.println(petList.get(i).getName() + " " + petList.get(i).speak()); }

Consider the following code segment, which is intended to display 6.0. double fact1 = 1 / 2; double fact2 = 3 * 4; double product = fact1 * fact2; System.out.println(product); Which of the following best describes the error, if any, in the code segment?

B. Either the numerator or the denominator of the fraction 1 / 2 should be cast as double.

Consider the following code segment. int x = 10; int y = 20; /* missing code */ System.out.print(top / bottom); Which of the following replacements for /* missing code */ will cause an ArithmeticException to occur? I. int top = x - y;int bottom = y - x; II. int top = 2 * x;int bottom = y - top; III. int top = x + y;int bottom = 2 * top;

B. II only

Which statement correctly declares a variable that can store a temperature rounded to the nearest tenth of a degree?

B. double patientTemp;

Consider the following code segment. int a = 1; int b = 2; int c = 3; int d = 4; double x = a + b * c % d; What is the value of x when the code segment has been executed?

C. 3.0

The volume of a cylinder is equal to the height times the area of the circular base. The area of the circular base is equal to π (pi) times the square of the radius. The code segment below is intended to compute and print the volume of a cylinder with radius r and height h. Assume that the double variables r, h, and pi have been properly declared and initialized. /* missing code */ System.out.print(volume); Which of the following can be used to replace /* missing code */ so that the code segment works as intended? I. double baseArea = pi * r * r;double volume = baseArea * h; II. double volume = pi * r * r;volume = volume * h; III. double volume = pi * r * r * h;

E. I, II, and III

b.

Book book1 = new Book("Frankenstein", "Mary Shelley"); Book book2 = new PictureBook("The Wonderful Wizard of Oz", "L. Frank Baum", "W.W. Winslow");

Consider the following statement, which is intended to create an ArrayList named numbers that can be used to store Integer values. ArrayList<Integer> numbers = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended? new ArrayList() new ArrayList<Integer> new ArrayList<Integer>()

C. I and III only

Consider the following code segment. double p = 10.6; double n = -0.2; System.out.println((int) (p + 0.5)); System.out.print((int) (n - 0.5)); What is printed as a result of executing the code segment?

D. 11 0

Consider the following code segment. int m = 8; int n = 3; if (m + n > 10) { System.out.print(m + n); } if (m - n > 0) { System.out.print(m - n); } What, if anything, is printed as a result of executing the code segment?

D. 115

Consider the following code segment: /* data type 1 */ x = 0.5; /* data type 2 */ y = true; Which of the following best describes the data types that should be used to replace/* data type 1 */ and /* data type 2 */ so that the code segment compiles without error?

D. The variable x should be declared as a double and the variable y should be declared as a boolean.

Consider the following class definitions. public class Pet { public void speak() { System.out.print("pet sound"); } } public class Dog extends Pet { public void bark() { System.out.print("woof woof"); } public void speak() { bark(); } } public class Cat extends Pet { public void speak() { System.out.print("meow meow"); } } The following statement appears in a method in another class. myPet.speak(); Under which of the following conditions will the statement compile and run without error? I. When myPet is an object of type Pet II. When myPet is an object of type Dog III. When myPet is an object of type Cat

E. I, II, and III

Consider the following class definition. public class AnimalPrinter { public void printDog() { System.out.println("dog"); } public void printCat() { System.out.println("cat"); } /* constructors not shown */ } The method myMethod appears in a class other than AnimalPrinter. The method is intended to produce the following output. dog cat Assume that an AnimalPrinter object myPrinter has been properly declared and initialized inside myMethod. Which of the following code segments, if located in myMethod, will produce the intended output?

E. myPrinter.printDog();myPrinter.printCat();

In the code segment below, numList is an ArrayList of integers that is sorted in descending order. The code segment is intended to insert the integer value val into numList so that numList is still sorted in descending order. int j = 0; while (val != numList.get(j)) { j++; } numList.add(j, val); The code segment does not always work as intended. Assuming that numList has been initialized to {3, 2, 1, 0}, for which value of val does the code segment NOT produce the expected result?A

A. 4

Consider the following class definitions. public class Bike { private int numWheels = 2; // No constructor defined } public class EBike extends Bike { private int numBatteries; public EBike(int batteries) { numBatteries = batteries; } } The following code segment appears in a method in a class other than Bike or EBike. EBike eB = new EBike(4); Which of the following best describes the effect of executing the code segment?

A. An implicit call to the zero-parameter Bike constructor initializes the instance variable numWheels. The instance variable numBatteries is initialized using the value of the parameter batteries.

Consider the following method countNegatives, which searches an ArrayList of Integer objects and returns the number of elements in the list that are less than 0. public static int countNegatives(ArrayList<Integer> arr) { int count = 0; for (int j = 0; j < arr.size(); j++) // Line 4 { if (arr.get(j) < 0) { count++; } } return count; } Which of the following best explains the impact to the countNegatives method when, in line 4, j < arr.size() is replaced with j <= arr.size() - 1 ?

A. It has no impact on the behavior of the method.

Consider the following class definition. public class Backyard { private int length; private int width; public Backyard(int l, int w) { length = l; width = w; } public int getLength() { return length; } public int getWidth() { return width; } public boolean equals(Object other) { if (other == null) { return false; } Backyard b = (Backyard) object; return (length == b.getLength() && width == b.getWidth()); } } The following code segment appears in a class other than Backyard. It is intended to print true if b1 and b2 have the same lengths and widths, and to print false otherwise. Assume that x, y, j, and k are properly declared and initialized variables of type int. Backyard b1 = new Backyard(x, y); Backyard b2 = new Backyard(j, k); System.out.println( /* missing code */ ); Which of the following can be used as a replacement for /* missing code */ so the code segment works as intended?

B. b1.equals(b2)

Consider the following method. public static int mystery(ArrayList<Integer> numList) { if (numList.size() == 0) { return 0; } else { int val = numList.remove(0); return val + mystery(numList); } } Which of the following best describes the value returned by the method?

C. It returns the sum of the elements in numList.

Consider the following class definition. public class Silly { private int var1; private String var2; public Silly(int v1, String v2) { var1 = v1; var2 = v2; } public boolean equals(Object other) { if (other == null) { return false; } Silly s = (Silly) other; return (var1 == s.var1 && var1 == var2.length() && var2.length() == s.var2.length()); } } The following code segment appears in a class other than Silly. Silly s1 = new Silly(3, "abcd"); Silly s2 = new Silly(3, "abcd"); Silly s3 = new Silly(5, "vwxyz"); Silly s4 = new Silly(5, "aaaaa"); Silly s5 = new Silly(5, "efg"); Which of the following Boolean expressions will evaluate to true ?

C. s3.equals(s4)

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided?

D. 0 <= index < phrase.length() - key.length()

Consider the following class declarations. public class Person { public void laugh() { System.out.print("Hahaha"); } } public class EvilPerson extends Person { public void laugh() { System.out.print("Mwahahaha"); } } public class Henchman extends EvilPerson { // No methods defined } The following code segment appears in a method in another class. alice.laugh(); Under which of the following conditions will the code segment print "Mwahahaha" ? I. When alice has been declared as type Person II. When alice has been declared as type EvilPerson III. When alice has been declared as type Henchman

D. II and III only

Consider the following class definitions. public class Bird { private int beakStrength; public void Bird(int input) { beakStrength = input; } public void setBeakStrength(int strength) { beakStrength = strength; } } public class Hawk extends Bird { private int talonStrength; public Hawk(int talon, int beak) { super(beak); talonStrength = talon; } } The following statement appears in a method in another class. Bird b = new Hawk(5, 8); Which of the following best describes the effect of executing the statement?

D. The Bird variable b is instantiated as a Hawk. The call super(beak) invokes the Bird constructor and initializes the instance variable beakStrength with the value from the parameter beak. The instance variable talonStrength is then initialized with the value from the parameter talon.

Consider the following class. public class Help { private int h; public Help(int newH) { h = newH; } public double getH() { return h; } } The getH method is intended to return the value of the instance variable h. The following code segment shows an example of creating and using a Help object. Help h1 = new Help(5); int x = h1.getH(); System.out.println(x); Which of the following statements best explains why the getH method does not work as intended?

D. The getH method should have a return type of int.

Consider the following class declaration. public class Student { private String name; private int age; public Student(String n, int a) { name = n; age = a; } public boolean isOlderThan5() { if (age > 5) { return true; } } } Which of the following best describes the reason this code segment will not compile?

D. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.

Consider the following classes. public class Bird { public void sing() { System.out.println("Cheep"); } } public class Duck extends Bird { public void sing() { System.out.println("Quack"); } } public class Chicken extends Bird { // No methods defined } public class Rooster extends Chicken { public void sing() { System.out.println("Cockadoodle doo"); } } The following statement appears in a method in another class. someBird.sing(); Under which of the following conditions will the statement compile and run without error? I. When someBird has been declared as type Duck II. When someBird has been declared as type Chicken III. When someBird has been declared as type Rooster

E. I, II, and III

The Thing class below will contain a String attribute, a constructor, and the helper method, which will be kept internal to the class. public class Thing { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

B. private String str; public Thing(String s) { /* implementation not shown */ } private void helper() { /* implementation not shown */ }

In the following code segment, assume that the ArrayList data has been initialized to contain the Integer values [4, 3, 4, 5, 3, 4]. int j = 0; while (j < data.size() - 1) { if (data.get(j) > data.get(j + 1)) { System.out.print(data.get(j + 1) + " "); } j++; } What, if anything, is printed as a result of executing the code segment?

A. 3 3

Consider the following code segment. System.out.print("Ready"); // Line 1 System.out.print("Set"); // Line 2 System.out.print("Go!"); // Line 3 The code segment is intended to produce the following output but may not work as intended. Ready Set Go! Which change, if any, can be made so that the code segment produces the intended output?

A. Changing print to println in lines 1 and 2

Consider the following two code segments. Assume that variables x and y have been declared as int variables and have been assigned integer values. I. int result = 0; if (x > y) { result = x - y; System.out.print(result); } else if (x < y) { result = y - x; System.out.print(result); } else { System.out.print(result); } II. if (x < y) { System.out.print(y - x); } else { System.out.print(x - y); } Which of the following correctly compares the outputs of the two code segments?

A. Code segment I and code segment II produce the same output for all values of x and y.

Consider the following class definitions. public class First { public void output1() { output2(); } public void output2() { output3(); } public void output3() { System.out.print("First"); } } public class Second extends First { public void output() { output1(); output2(); output3(); } } public class Third extends Second { public void output3() { System.out.print("Third"); } } The following code segment appears in a class other than First, Second, or Third. First sec = new Second(); // Line 1 Second thr = new Third(); // Line 2 sec.output(); // Line 3 thr.output(); // Line 4 Which of the following best explains why the code segment will not compile?

A. Line 3 causes a compile-time error because the variable sec should be declared as type Second.

In the following expression, sweet, salty, and sour are properly declared and initialized boolean variables. sweet && (salty || sour) Which of the following expressions is equivalent to the expression above?

B. (sweet && salty) || (sweet && sour)

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following code segment appears in a method in the same class as bSearch. int[] nums = {10, 20, 30, 40, 50}; int result = bSearch(nums, 0, nums.length - 1, 40); How many times will the bSearch method be called as a result of executing the code segment, including the initial call?

B. 2

Consider the following method, inCommon, which takes two Integer ArrayList parameters. The method returns true if the same integer value appears in both lists at least one time, and false otherwise. public static boolean inCommon(ArrayList<Integer> a, ArrayList<Integer> b) { for (int i = 0; i < a.size(); i++) { for (int j = 0; j < b.size(); j++) // Line 5 { if (a.get(i).equals(b.get(j))) { return true; } } } return false; } Which of the following best explains the impact to the inCommon method when line 5 is replaced by for (int j = b.size() - 1; j > 0; j--) ?

B. After the change, the method will never check the first element in list b.

Consider the following class declarations. public class ParentClass { public void wheelsOnTheBus() { System.out.println("round and round"); } } public class SubClass extends ParentClass { public void wheelsOnTheBus() { System.out.println("are flat"); } } public class SubSubClass extends ParentClass { public void wheelsOnTheBus() { // No methods defined } } The following code segment appears in a method in another class. obj.wheelsOnTheBus(); Under which of the following conditions will the code segment print "are flat" ? I. when obj has been declared as type ParentClass II. when obj has been declared as type SubClass III. when obj has been declared as type SubSubClass

B. II only

Consider the following class declarations. public class Tree { private String treeVariety; public Tree() { treeVariety = "Oak"; } public Tree(String variety) { treeVariety = variety; } } public class DeciduousTree extends Tree { public DeciduousTree(String variety) { super(); } } public class EvergreenTree extends Tree { public EvergreenTree(String variety) { super(variety); } } The following code segment appears in a method in another class. DeciduousTree tree1 = new DeciduousTree("Maple"); EvergreenTree tree2 = new EvergreenTree("Fir"); Which of the following best describes the result of executing the code segment?

B. Object tree1 is created using the DeciduousTree constructor, which uses super to set tree1's treeVariety attribute to "Oak". Object tree2 is created using the EvergreenTree constructor, which uses super to set tree2's treeVariety attribute to "Fir".

Consider the following class declarations. public class Dog { private String name; public Dog() { name = "NoName"; } } public class Poodle extends Dog { private String size; public Poodle(String s) { size = s; } } The following statement appears in a method in another class. Poodle myDog = new Poodle("toy"); Which of the following best describes the result of executing the statement?

B. The Poodle variable myDog is instantiated as a Poodle. The instance variable size is initialized to "toy". An implicit call to the no-argument Dog constructor is made, initializing the instance variable name to "NoName".

A store sells rope only in whole-foot increments. Given three lengths of rope, in feet, the following code segment is intended to display the minimum length of rope, in feet, that must be purchased so that the rope is long enough to be cut into the three lengths. For example, for lengths of 2.8 feet, 3 feet, and 5 feet, the minimum length of rope that must be purchased is 11 feet. For these inputs, the code segment should display 11. As another example, for lengths of 1.1 feet, 3.2 feet, and 2 feet, the minimum length of rope that must be purchased is 7 feet. For these inputs, the code segment should display 7. double len1; double len2; double len3; double total = len1 + len2 + len3; int minLength = (int) (total + 0.5); System.out.print(minLength); Which of the following best describes the behavior of the code segment?

B. The code segment works as intended but only when the sum of the three lengths is an integer or the decimal part of the sum of the three lengths is greater than or equal to 0.5.

Consider the method sequentialSearch, which takes an ArrayList of Integer elements and an int value as parameters and returns the index of the first appearance of the target value in the list or -1 if the target value does not appear in the list. public static int sequentialSearch(ArrayList<Integer> elements, int target) { for (int j = 0; j < elements.size(); j++) // Line 3 { if (elements.get(j) == target) { return j; } } return -1; } Which of the following explains how replacing Line 3 with for (int j = (elements.size() - 1); j >= 0; j--) will affect the behavior of sequentialSearch?

B. The modified method will return the index of the last appearance of the target value in the list, or -1 if the target value does not appear in the list.

The Fraction class below will contain two int attributes for the numerator and denominator of a fraction. The class will also contain a method fractionToDecimal that can be accessed from outside the class. public class Fraction { /* missing code */ // constructor and other methods not shown } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

B. private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

Consider the following code segment. String myString = new String("my string"); String yourString = new String(); yourString = "my string"; boolean dotEquals = myString.equals(yourString); boolean equalsEquals = (myString == yourString); System.out.print(dotEquals + " " + equalsEquals); What is printed as a result of executing the code segment?

B. true false

Consider the following method, remDups, which is intended to remove duplicate consecutive elements from nums, an ArrayList of integers. For example, if nums contains {1, 2, 2, 3, 4, 3, 5, 5, 6}, then after executing remDups(nums), nums should contain {1, 2, 3, 4, 3, 5, 6}. public static void remDups(ArrayList<Integer> nums) { for (int j = 0; j < nums.size() - 1; j++) { if (nums.get(j).equals(nums.get(j + 1))) { nums.remove(j); j++; } } } The code does not always work as intended. Which of the following lists can be passed to remDups to show that the method does NOT work as intended?

B. {1, 2, 2, 3, 3, 4, 5}

Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers. /** Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length) * arr.length == temp.length */ public static void mergeSortHelper(int[] arr, int from, int to, int[] temp) { if (from < to) { int middle = (from + to) / 2; mergeSortHelper(arr, from, middle, temp); mergeSortHelper(arr, middle + 1, to, temp); merge(arr, from, middle, to, temp); } } The merge method is used to merge two halves of an array (arr[from] through arr[middle], inclusive, and arr[middle + 1] through arr[to], inclusive) when each half has already been sorted into ascending order. For example, consider the array arr1, which contains the values {1, 3, 5, 7, 2, 4, 6, 8}. The lower half of arr1 is sorted in ascending order (elements arr1[0] through arr1[3], or {1, 3, 5, 7}), as is the upper half of arr1 (elements arr1[4] through arr1[7], or {2, 4, 6, 8}). The array will contain the values {1, 2, 3, 4, 5, 6, 7, 8} after the method call merge(arr1, 0, 3, 7, temp). The array temp is a temporary array declared in the calling program. Consider the following code segment, which appears in a method in the same class as mergeSortHelper and merge. int[] numbers = {40, 10, 20, 30}; int[] temp = new int[numbers.length]; mergeSortHelper(numbers, 0, numbers.length - 1, temp); How many times will the merge method be called as a result of executing the code segment?

C. 3

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following statement appears in a method in the same class as bSearch. Assume that nums is a sorted array of length 7, containing only positive integers. int result = bSearch(nums, 0, nums.length - 1, -100); How many times will the bSearch method be called as a result of executing the statement, including the initial call?

C. 4

Consider the following method, which implements a recursive binary search. /** Returns an index in myList where target appears, * if target appears in myList between the elements at indices * low and high, inclusive; otherwise returns -1. * Precondition: myList is sorted in ascending order. * low >= 0, high < myList.size(), myList.size() > 0 */ public static int binarySearch(ArrayList<Integer> myList, int low, int high, int target) { int mid = (high + low) / 2; if (target < myList.get(mid)) { return binarySearch(myList, low, mid - 1, target); } else if (target > myList.get(mid)) { return binarySearch(myList, mid + 1, high, target); } else if (myList.get(mid).equals(target)) { return mid; } return -1; } Assume that inputList is an ArrayList of Integer objects that contains the following values. [0, 10, 30, 40, 50, 70, 70, 70, 70] What value will be returned by the call binarySearch(inputList, 0, 8, 70) ?

C. 6

Consider the following class definitions. public class Computer { private String memory; public Computer() { memory = "RAM"; } public Computer(String m) { memory = m; } public String getMemory() { return memory; } } public class Smartphone extends Computer { private double screenWidth, screenHeight; public SmartPhone(double w, double h) { super("flash"); screenWidth = w; screenHeight = h; } public double getScreenWidth() { return screenWidth; } public double getScreenHeight() { return screenHeight; } } The following code segment appears in a class other than Computer or Smartphone. Computer myPhone = new SmartPhone(2.55, 4.53); System.out.println("Device has memory: " + myPhone.getMemory() + ", screen area: " + myPhone.getScreenWidth() * myPhone.getScreenHeight() + " square inches."); The code segment is intended to produce the following output. Device has memory: flash, screen area: 11.5515 square inches. Which of the following best explains why the code segment does not work as intended?

C. An error occurs during compilation because the getScreenWidth and getScreenHeight methods are not defined for the Computer object myPhone.

Consider the following class declarations. public class Range { private int lowValue; public Range(int low) { lowValue = low; } public String toString() { return "This range starts with " + lowValue; } } public class ClosedRange extends Range { private int highValue; public ClosedRange(int low, int high) { super(low); highValue = high; } public String toString() { return super.toString() + " and ends with " + highValue; } } A code segment appearing in a method in another class is intended to produce the following output. This range starts with 1 and ends with 10 Which of the following code segments will produce this output?

C. ClosedRange r3 = new ClosedRange(1, 10); System.out.println(r3);

Consider the following Vbox class. public class Vbox { private int width; private int height; private int depth; public Vbox(int w, int h, int d) { width = w; height = h; depth = d; } public Vbox(int len) { width = len; height = len; depth = len; } } Which of the following declarations, appearing in a method in a class other than Vbox, will correctly instantiate a Vbox object? I. Vbox b1 = new Vbox(4); II. Vbox b2 = new Vbox(2, 8, 4); III. Vbox b3 = new Vbox(4.0, 4.0, 4.0);

C. I and II only

Consider the following class declarations. public class A { private int x; public A() { x = 0; } public A(int y) { x = y; } // There may be instance variables, constructors, and methods that are not shown. } public class B extends A { private int y; public B() { /* missing code */ } // There may be instance variables, constructors, and methods that are not shown. } Which of the following can be used to replace /* missing code */ so that the statement B temp = new B(); will construct an object of type B and initialize both x and y with 0 ? y = 0 super (0); y = 0; x = 0; y = 0;

C. I and II only

Consider the following class definitions. public class Apple { public void printColor() { System.out.print("Red"); } } public class GrannySmith extends Apple { public void printColor() { System.out.print("Green"); } } public class Jonagold extends Apple { // no methods defined } The following statement appears in a method in another class. someApple.printColor(); Under which of the following conditions will the statement print "Red" ? I. When someApple is an object of type Apple II. When someApple is an object of type GrannySmith III. When someApple is an object of type Jonagold

C. I and III only

Consider the following method findValue, which takes an ArrayList of String elements and a String value as parameters and returns true if the String value is found in the list and false otherwise. public static boolean findValue(ArrayList<String> arr, String key) { for (int j = 0; j < arr.size(); j++) // Line 3 { if (arr.get(j).equals(key)) { return true; } } return false; } Which of the following best explains the impact to the findValue method when, in line 3, int j = 0 is replaced by int j = 1 ?

C. It will cause the method to return a different result when the key value is found only at the first index in the list.

Consider the following class declarations. public class Publication { private String title; public Publication() { title = "Generic"; } public Publication(String t) { title = t; } } public class Book extends Publication { public Book() { super(); } public Book(String t) { super(t); } } The following code segment appears in a method in another class. Book myBook = new Book("Adventure Story"); // Line 1 Book yourBook = new Book(); // Line 2 Which of the following best describes the result of executing the code segment?

C. Object myBook is created using the one-argument Book constructor, which uses super to set myBook's title attribute to "Adventure Story". Object yourBook is created using super to call to the Publication no-argument constructor to set yourBook's title attribute to "Generic".

Consider the following search method. public static int search(int[] arr, int target) { int result = -1; for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { result = j; // Line 8 } } return result; } Which of the following describes the effect of replacing the statement in line 8 of the method with result = arr[j]; ?

C. The modified method will return target if target appears in arr and will return -1 otherwise.

Consider the following class definitions. public class Book { private String bookTitle; public Book() { bookTitle = ""; } public Book(String title) { bookTitle = title; } } public class TextBook extends Book { private String subject; public TextBook(String theSubject) { subject = theSubject; } } The following code segment appears in a method in a class other than Book or TextBook. Book b = new TextBook("Psychology"); Which of the following best describes the effect of executing the code segment?

C. There is an implicit call to the zero-parameter Book constructor. The instance variable bookTitle is then initialized to "". Then, the instance variable subject is initialized with the value of the parameter theSubject.

Consider the following method definition. The method isReversed is intended to return true if firstList and secondList contain the same elements but in reverse order, and to return false otherwise. /** Precondition: firstList.size() == secondList.size() */ public static boolean isReversed(ArrayList<Integer> firstList, ArrayList<Integer> secondList) { for (int j = 0; j < firstList.size() / 2; j++) { if (firstList.get(j) != secondList.get(secondList.size() - 1 - j)) { return false; } } return true; } The method does not always work as intended. For which of the following inputs does the method NOT return the correct value?

C. When firstList is {1, 3, 5, 7} and secondList is {5, 5, 3, 1}

Consider the following class definition. public class Beverage { private int temperature; public Beverage(int t) { temperature = t; } public int getTemperature() { return temperature; } public boolean equals(Object other) { if (other == null) { return false; } Beverage b = (Beverage) other; return (b.getTemperature() == temperature); } } The following code segment appears in a class other than Beverage. Assume that x and y are properly declared and initialized int variables. Beverage hotChocolate = new Beverage(x); Beverage coffee = new Beverage(y); boolean same = /* missing code */; Which of the following can be used as a replacement for /* missing code */ so that the boolean variable same is set to true if and only if the hotChocolate and coffee objects have the same temperature values?

C. hotChocolate.equals(coffee)

Consider the following method, which is intended to return the largest value in the portion of the int array data that begins at the index start and goes to the end of the array. /** Precondition: 0 <= start < data.length */ public int maximum(int[] data, int start) { if (start == data.length - 1) { return data[start]; } /* missing statement */ if (val > data[start]) { return val; } else { return data[start]; } } Which of the following can be used as a replacement for /* missing statement */ so that the maximum method works as intended?

C. int val = maximum(data, start + 1);

Consider the following class definition. public class Person { private String name; /* missing constructor */ } The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington"); Which of the following can be used to replace /* missing constructor */ so that the object p is correctly created?

C. public Person(String n) { name = n; }

Consider the following method. public static void strChange(String str) { if (str.length() > 0) { strChange(str.substring(1)); System.out.print(str.substring(0, 1)); } } Which of the following best describes the behavior of the method?

D. It prints the characters of str in reverse order.

Consider the following method. /* Precondition: j <= k */ public static void mystery(int j, int k) { System.out.println(j); if (j < k) { mystery(j + 1, k); } } Which of the following best describes the behavior of the mystery method?

D. It prints the integers from j to k, inclusive, in order from least to greatest.

Consider the following class definitions. public class Appliance { private int id; private String brand; public Appliance(int aId, String aBrand) { /* implementation not shown */ } public String display() { /* implementation not shown */ } } public class Refrigerator extends Appliance { private int numOfDoors; public Refrigerator(int rId, String rBrand, int rNumOfDoors) { /* implementation not shown */ } } The following code segment appears in a class other than Appliance or Refrigerator. public static void displayFeatures(Refrigerator r) { System.out.println(r.display()); // Line 3 } Appliance a1 = new Refrigerator(456, "AllBrand", 2); // Line 6 Refrigerator a2 = new Refrigerator(789, "Xtreme", 3); // Line 7 displayFeatures(a1); // Line 8 displayFeatures(a2); // Line 9 Which of the following best explains why the code segment will not compile?

D. Line 8 causes a compile-time error because the parameter a1 in the call displayFeatures(a1) has the incorrect data type.

Consider the following class definitions. public class Person { private String firstName; private String lastName; public Person(String pFirstName, String pLastName) { firstName = pFirstName; lastName = pLastName; } public void personInfo() { System.out.println("My name is " + firstName + " " + lastName); } } pubic class Teacher extends Person { private String school; private String subject; public Teacher(String tFN, String tLN, String tSchool, String tSubject) { super(tFN, tLN); school = tSchool; subject = tSubject; } public void teacherInfo() { personInfo(); System.out.println("I teach " + subject + " at " + school); } } The following code segment appears in a class other than Person or Teacher. Person teach = new Teacher("Henry", "Lowe", "PS 150", "English"); teach.teacherInfo(); Which of the following best explains why the code segment will not compile?

D. The variable teach should be declared as a Teacher data type because teacherInfo is a method in the Teacher class.

Consider the following class declaration. public class Thing { private String color; public Thing() { color = "Blue"; } public Thing(String setColor) { color = setColor; } } Which of the following code segments, when appearing in a class other than Thing, would create a reference of type Thing with a value of null ?

D. Thing someThing;

Consider the following class definitions. public class Vehicle { private int numOfWheels; public Vehicle(int nNumOfWheels) { numOfWheels = nNumOfWheels; } public String toString() { return "Number of Wheels: " + numOfWheels; } } public class Motorized extends Vehicle { private int maxSpeed; public Motorized(int nNumOfWheels, nMaxSpeed) { super(nNumOfWheels); maxSpeed = nMaxSpeed; } public String toString() { String s = super.toString() + " Max Speed: "; if (maxSpeed <= 10) { s += "Slow"; } else if (maxSpeed > 10 && maxSpeed <= 100) { s += "Fast"; } else { s += "Super Speedy"; } return s; } } Which of the following code segments, when executed in a class other than Vehicle or Motorized, will display Number of Wheels: 4 Max Speed: Fast ?

D. Vehicle obj = new Motorized(4, 55); System.out.println(obj);

Consider the following code segment. int a = 1; int b = 0; int c = -1; if ((b + 1) == a) { b++; c += b; } if (c == a) { a--; b = 4; } What are the values of a, b, and c after this code segment has been executed?

D. a = 1, b = 1, and c = 0

Consider the following code segment, which is intended to set the Boolean variable inRange to true if the integer value num is greater than min value and less than max value. Otherwise inRange is set to false. Assume that inRange, num, min, and max have been properly declared and initialized. boolean isBigger; boolean isSmaller; boolean inRange; if (num < max) { isSmaller = true; } else { isSmaller = false; } if (num > min) { isBigger = true; } else { isBigger = false; } if (isBigger == isSmaller) { inRange = true; } else { inRange = false; } Which of the following values of num, min, and max can be used to show that the code does NOT work as intended?

D. num = 50, min = 50, max = 50

Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers. /** Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length) * arr.length == temp.length */ public static void mergeSortHelper(int[] arr, int from, int to, int[] temp) { if (from < to) { int middle = (from + to) / 2; mergeSortHelper(arr, from, middle, temp); mergeSortHelper(arr, middle + 1, to, temp); merge(arr, from, middle, to, temp); } } The merge method is used to merge two halves of an array (arr[from] through arr[middle], inclusive, and arr[middle + 1] through arr[to], inclusive) when each half has already been sorted into ascending order. For example, consider the array arr1, which contains the values {1, 3, 5, 7, 2, 4, 6, 8}. The lower half of arr1 is sorted in ascending order (elements arr1[0] through arr1[3], or {1, 3, 5, 7}), as is the upper half of arr1 (elements arr1[4] through arr1[7], or {2, 4, 6, 8}). The array will contain the values {1, 2, 3, 4, 5, 6, 7, 8} after the method call merge(arr1, 0, 3, 7, temp). The array temp is a temporary array declared in the calling program. Consider the following code segment, which appears in a method in the same class as mergeSortHelper and merge. int[] vals = {80, 50, 30, 20, 60, 70}; int[] temp = new int[vals.length]; mergeSortHelper(vals, 0, vals.length - 1, temp); Which of the following represents the arrays merged the last time the merge method is executed as a result of the code segment above?

D. {30, 50, 80} and {20, 60, 70} are merged to form {20, 30, 50, 60, 70, 80}.

A school administrator has created a Student class. The class contains variables to represent the following. An int variable called studentID to represent the student's ID number A String variable called studentName to represent the student's name The school administrator has also created a Parent class. The class contains variables to represent the following. A String variable called parentName to represent the parent's name A String variable called email to represent the parent's e-mail address The object penelope will be declared as type Student. The object mrsPatel will be declared as type Parent. Which of the following descriptions is accurate?

E. An attribute of the mrsPatel object is email.

Consider the following class declarations. public class MultiTool { private int blade; private int screwdriver; public MultiTool(int b, int s) { blade = b; screwdriver = s; } } public class DeluxeMultiTool extends MultiTool { private boolean compass; public DeluxeMultiTool(int b, int s, boolean c) { super(b, s); compass = c; } public String getCompass() { return compass + ""; } } The following code segment appears in a method in another class. ArrayList<MultiTool> toolList = new ArrayList<MultiTool>(); MultiTool tool1 = new DeluxeMultiTool(4, 2, false); // Line 2 DeluxeMultiTool tool2 = new DeluxeMultiTool(3, 1, true); // Line 3 toolList.add(tool1); // Line 4 toolList.add(tool2); // Line 5 for (MultiTool tool : toolList) { System.out.println(tool.getCompass()); // Line 8 } The code segment does not compile. Which of the following best explains the cause of the error?

E. Line 8 causes a compile-time error because the getCompass method is not defined for objects of type MultiTool.

Consider the method seqSearch, which implements a sequential search algorithm. public int seqSearch(int[] arr, int target) { for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { return j; } } return -1; } Consider another method, seqSearch2, which modifies seqSearch to use an enhanced for loop. public int seqSearch2(int[] arr, int target) { for (int j : arr) { if (j == target) { return j; } } return -1; } Which of the following best describes the difference in the behavior of seqSearch2 relative to seqSearch as a result of the modification?

E. The modification in seqSearch2 will cause the value of target to be returned instead of the index of target in cases where target appears in arr.

Consider the following class declaration. public class VetRecord { private String name; private int age; private int weight; private boolean needsVaccine; public VetRecord(String nameP, int ageP, int weightP, boolean needsVaccineP) { name = nameP; age = ageP; weight = weightP; needsVaccine = needsVaccineP; } public VetRecord(String nameP, int ageP, int weightP) { name = nameP; age = ageP; weight = weightP; needsVaccine = true; } } A new constructor is to be added to the VetRecord class. Which of the following is NOT a possible header for the new constructor?

E. VetRecord(String nameP, int weightP, int ageP)

Consider the following code segment. ArrayList<Integer> vals = new ArrayList<Integer>(); vals.add(vals.size(), vals.size()); vals.add(vals.size() - 1, vals.size() + 1); vals.add(vals.size() - 2, vals.size() + 2); System.out.println(vals.toString()); What is printed as a result of executing the code segment?

E. [4, 2, 0]

Consider the following method, which takes as input a temperature in degrees Fahrenheit and returns the corresponding temperature in degrees Celsius. public double fahrenheitToCelsius(double f) { double c = (f - 32) * 5 / 9; return c; } Assume that each of the following code segments appears in a method in the same class as fahrenheitToCelsius. Which of the following code segments prints the temperature in degrees Celsius that corresponds to 32 degrees Fahrenheit?

E. double f = 32.0; double c = fahrenheitToCelsius(f); System.out.println(c);

Consider the following class definitions. public class Artifact { private String title; private int year; public Artifact(String t, int y) { title = t; year = y; } public void printInfo() { System.out.print(title + " (" + year + ")"); } } public class Artwork extends Artifact { private String artist; public Artwork(String t, int y, String a) { super(t, y); artist = a; } public void printInfo() { /* missing implementation */ } } The following code segment appears in a method in another class. Artwork starry = new Artwork("The Starry Night", 1889, "Van Gogh"); starry.printInfo(); The code segment is intended to produce the following output. The Starry Night (1889) by Van Gogh Which of the following can be used to replace /* missing implementation */ in the printInfo method in the Artwork class so that the code segment produces the intended output?

E. super.printInfo(); System.out.print(" by " + artist);

Part A: Write a statement to create a LightSequence object gradShow that has the initial light sequence "0101 0101 0101". Write the statement below.

LightSequence gradShow = new LightSequence("0101 0101 0101");

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. A set of classes using inheritance is used to represent animals observed at a wildlife sanctuary. A portion of the class hierarchy is shown in the following diagram. All Animal objects have the following attributes. A String variable indicating whether the animal is a carnivore or a herbivore A String variable representing the animal species (e.g., lion, giraffe, zebra) A String variable representing the name of the individual animal (e.g., Lisa, Gary, Percy) The Animal class also contains a toString method that indicates the state of an animal. The following table shows the intended behavior of the Animal class. StatementResultAnimal lisa = new Animal("carnivore", "lion", "Lisa");A new Animal object is created.lisa.toString();The string "Lisa the lion is a carnivore" is returned. (a) Write the complete Animal class. Your implementation must meet all specifications and conform to the behavior shown in the table. The Herbivore class is a subclass of Animal. The Herbivore class does not contain any attributes or methods other than those found in the Animal class. The constructor to the Herbivore class accepts two parameters for the species and name of the herbivore. The constructor passes those parameters along with the string literal "herbivore" to the Animal class to construct the object. The following table shows the intended behavior of the Herbivore class. StatementResultHerbivore gary = new Herbivore("giraffe", "Gary");A new Herbivore object is created.gary.toString();The string "Gary the giraffe is aherbivore" is returned. (b) Write the complete Herbivore class. Your implementation must meet all specifications and conform to the behavior shown in the table. The Elephant class is a subclass of Herbivore. The Elephant class contains one additional attribute not found in Herbivore: a double variable representing the length of the elephant's tusks, in meters. The constructor to the Elephant class accepts two parameters for the name and tusk length of the elephant. The constructor passes those parameters along with the string literal "elephant" to the Herbivore class to construct the object. The following table shows the intended behavior of the Elephant class. StatementResultElephant percy = new Elephant("Percy", 2.0);A new Elephant object is created.percy.toString();The string "Percy the elephant is aherbivore with tusks 2.0 meters long" is returned. (c) Write the complete Elephant class. Your implementation must meet all specifications and conform to the behavior shown in the table.

answers below

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. The following Book class is used to represent books and print information about each book. Each Book object has attributes for the book title and for the name of the book's author. public class Book { private String title; private String author; public Book(String t, String a) { title = t; author = a; } public void printBookInfo() { System.out.print(title + ", written by " + author); } } (a) The PictureBook class is a subclass of the Book class that has one additional attribute: a String variable named illustratorthat is used to represent the name of the illustrator of a picture book. The PictureBook class also contains a printBookInfomethod to print the title, writer, and illustrator of a picture book. Consider the following code segment. PictureBook myBook = new PictureBook("Peter and Wendy", "J.M. Barrie", "F.D. Bedford"); myBook.printBookInfo(); The code segment is intended to print the following output. Peter and Wendy, written by J.M. Barrie and illustrated by F.D. Bedford Complete the PictureBook class below. Your implementation should conform to the example above. public class PictureBook extends Book Consider the following books. A book titled Frankenstein, written by Mary Shelley A picture book titled The Wonderful Wizard of Oz, written by L. Frank Baum and illustrated by W.W. Denslow The following code segment is intended to represent the two books described above as objects book1 and book2, respectively, and add them to the ArrayList myLibrary. ArrayList<Book> myLibrary = new ArrayList<Book>(); /* missing code */ myLibrary.add(book1); myLibrary.add(book2); (b) Write a code segment that can be used to replace /* missing code */ so that book1 and book2 will be correctly created and added to myLibrary. Assume that class PictureBook works as intended, regardless of what you wrote in part (a). The BookListing class is used to generate a descriptive listing for a book. The BookListing constructor takes a Book object and a double value as parameters and uses them to print information about the book, along with its price. Assume that book1 and book2 were created as specified in part (b). The following table demonstrates the intended behavior of the BookListing class using objects book1 and book2. Code SegmentResult PrintedBookListing listing1 = new BookListing(book1, 10.99);listing1.printDescription();Frankenstein, written by Mary Shelley, $10.99BookListing listing2 = new BookListing(book2, 12.99);listing2.printDescription();The Wonderful Wizard of Oz, written by L. Frank Baum and illustrated by W.W. Denslow, $12.99 (c) Complete the BookListing class below. Your implementation should conform to the examples. Assume that class PictureBookworks as intended, regardless of what you wrote in part (a). public class BookListing

answers below

1. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a-z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment. fading trailing batting Write the code segment as described above. The code segment must use an enhanced for loop to earn full credit.

for (String str : words) { if(str.substring(str.length - 3).equals("ing")) { System.out.println(str); } |

Part B: Write a statement that will call the display method to display the light sequence for the gradShow object. Write the statement below.

gradShow.display();

Question 1 Item 1 Question 1 SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. This question involves the creation of user names for an online system. A user name is created based on a user's first and last names. A new user name cannot be a duplicate of a user name already assigned. You will write the constructor and one method of the UserName class. A partial declaration of the UserName class is shown below. public class UserName { // The list of possible user names, based on a user's first and last names and initialized by the constructor. private ArrayList<String> possibleNames; /** Constructs a UserName object as described in part (a). * Precondition: firstName and lastName have length greater than 0 * and contain only uppercase and lowercase letters. */ public UserName(String firstName, String lastName) { /* to be implemented in part (a) */ } /** Returns true if arr contains name, and false otherwise. */ public boolean isUsed(String name, String[] arr) { /* implementation not shown */ } /** Removes strings from possibleNames that are found in usedNames as described in part (b). */ public void setAvailableUserNames(String[] usedNames) { /* to be implemented in part (b) */ } } (a) Write the constructor for the UserName class. The constructor initializes and fills possibleNames with possible user names based on the firstName and lastNameparameters. The possible user names are obtained by concatenating lastName with different substrings of firstName. The substrings begin with the first character of firstNameand the lengths of the substrings take on all values from 1 to the length of firstName. The following example shows the contents of possibleNames after a UserName object has been instantiated. Example UserName person = new UserName("john", "smith"); After the code segment has been executed, the possibleNames instance variable of person will contain the following String objects in some order. "smithj", "smithjo", "smithjoh", "smithjohn" Write the UserName constructor below. /** Constructs a UserName object as described in part (a). * Precondition: firstName and lastName have length greater than 0 * and contain only uppercase and lowercase letters. */ public UserName(String firstName, String lastName)

if(this.isValid(firstName) && this.isValidName(lastName)) { possibleNames = new ArrayList<String>(); for(int i = 1,; i < firstName.length; i++) { possibleNames.add(lastName+firstName.substring(0,i)); } } else { System.out.println("firstName and lastName must contain letters only."); }

(c) A programmer would like to add a method called getMostLuggageCapacity, which returns a Flight object that can carry the greatest amount of luggage, by weight. Write a description of how you would change the Flight and Airport classes in order to support this modification. Make sure to include the following in your response. Write the method header for the getMostLuggageCapacity method. Identify any new or modified variables, constructors, or methods aside from the getMostLuggageCapacity method. Do not write the program code for this change. Describe, for each new or revised variable, constructor, or method, how it would change or be implemented, including visibility and type. You do not need to describe the implementation of the getMostLuggageCapacity method. Do not write the program code for this change.

public Flight getMostLuggageCapacity() The Flight class would have to be changed by adding a private instance variable luggage and a public getLuggage() method. This method should return the amount of luggage carried by a flight. The Airport class would be where the getMostLuggageCapacity() method would be added because it has an array list of Flight objects. This list can then be iterated over to compare each flight's luggage capacity.

a.

public class PictureBook extends Book { private String illustrator; public PictureBook(String t, String a, String i) { super(t,a); illustrator = i; } public void printBookInfo() { super.printBookInfo(); System.out.print(" and illustrated by " + illustrator); } }

(a) Write the Airport method getTotalRevenue. The method returns the total revenue for all flights into and out of the airport. Revenue for a flight is the product of the number of passengers on the flight and the price of a seat on the flight. All seats on a flight have the same price. Some flights sell more seats than there is capacity for, since passengers sometimes cancel or modify reservations. If there are more passengers on a flight than the flight has capacity for, the revenue for the flight is the product of the capacity and the price of a seat on the flight. For example, assume that capitalHub has been declared as an Airport object and ArrayList allFlights contains the following flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 10Price: 100.50Capacity: 60Number of Passengers: 50Price: 200.00Capacity: 40Number of Passengers: 20Price: 100.00Capacity: 120 The following table shows the revenue that would be generated by each flight in allFlights. Number of PassengersPrice of a SeatCapacityRevenue Calculation2525$50.00$50.00303025×$50.00=$1,250.0025×$50.00=$1,250.001010$100.50$100.50606010×$100.50=$1,005.0010×$100.50=$1,005.005050$200.00$200.00404040×$200.00=$8,000.0040×$200.00=$8,000.002020$100.00$100.0012012020×$100.00=$2,000.0020×$100.00=$2,000.00 The call capitalHub.getTotalRevenue() should return the value 12255.0. Complete method getTotalRevenue. /** Returns the revenue generated by all flights at the airport, as described in part (a) */ public double getTotalRevenue()

public double getTotalRevenue() { double totalRev = 0; for(Flight f : allFlights) { if(f.getNumPassengers() > f.getCapacity()) { totalRev += f.getPrice() * f.getCapacity(); } else { totalRev += f.getPrice() * f.getNumPassengers(); } } return totalRev; }

Question 2 Sparse Array Part A: getValueAt Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.Notes: Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. A two-dimensional array of integers in which most elements are zero is called a sparse array. Because most elements have a value of zero, memory can be saved by storing only the non-zero values along with their row and column indexes. The following complete SparseArrayEntry class is used to represent non-zero elements in a sparse array. A SparseArrayEntry object cannot be modified after it has been constructed. The SparseArray class represents a sparse array. It contains a list of SparseArrayEntry objects, each of which represents one of the non-zero elements in the array. The entries representing the non-zero elements are stored in the list in no particular order. Each non-zero element is represented by exactly one entry in the list. The following table shows an example of a two-dimensional sparse array. Empty cells in the table indicate zero values. The sample array can be represented by a SparseArray object, sparse, with the following instance variable values. The items in entries are in no particular order; one possible ordering is shown below. (a) Write the SparseArray method getValueAt. The method returns the value of the sparse array element at a given row and column in the sparse array. If the list entries contains an entry with the specified row and column, the value associated with the entry is returned. If there is no entry in entries corresponding to the specified row and column, 0 is returned.In the example above, the call sparse.getValueAt(3, 1) would return -9, and sparse.getValueAt(3, 3) would return 0. Complete method getValueAt below. (b) Write the SparseArray method removeColumn. After removing a specified column from a sparsearray: All entries in the list entries with column indexes matching col are removed from the list. All entries in the list entries with column indexes greater than col are replaced by entries with column indexes that are decremented by one (moved one column to the left). The number of columns in the sparse array is adjusted to reflect the column removed. The sample object sparse from the beginning of the question is repeated for your convenience. The shaded entries in entries, below, correspond to the shaded column above. When sparse has the state shown above, the call sparse.removeColumn(1) could result insparse having the following values in its instance variables (since entries is in no particular order, itwould be equally valid to reverse the order of its two items). The shaded areas below show the changes.

public int getValueAt(int row, int col) { for(SparseArrayEntry e : entries) { if(e.getRow() == row && e.getCol() == col) { return e.getValue(); } } return 0; }

(b) Write the Airport method updateFlights. The method removes from the ArrayList allFlights any flight where the number of passengers is less than 2020 percent of the total capacity. The method should return the total number of passengers whose flight was removed. For example, assume that capitalHub has been declared as an Airport object and ArrayList allFlights contains the following flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 10Price: 100.50Capacity: 60Number of Passengers: 50Price: 200.00Capacity: 40Number of Passengers: 20Price: 100.00Capacity: 120 The call capitalHub.updateFlights() should return the value 30, and after the method finished executing, the ArrayList allFlights should contain the following two flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 50Price: 200.00Capacity: 40 Complete method updateFlights. /** Updates the list of flights by removing certain flights and returns the total number of * passengers whose flights were removed, as described in part (b) */ public int updateFlights()

public int updateFlights() { int sum = 0; for(int k = allFlights.size() - 1; k >= 0; k--) { Flight temp = allFlights.get(k); int min = (int) (temp.getCapacity() * .2); int pass = temp.getNumPassengers(); if(pass < min) { sum+= pass; allFlights.remove(k); } } return sum; }

Part C: isDiverse A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false. Assume that arraySum and rowSums work as specified, regardless of what you wrote in parts (a) and(b). You must use rowSums appropriately to receive full credit.Complete method isDiverse below. / * * Returns true if all rows in arr2D have different row sums;* false otherwise. * /public static boolean isDiverse(int [ ] [ ] arr2D)

public static boolean isDiverse(int[][] arr2D) { int[] sums = rowSums(arr2D); for(int i = 0; i < sums.length; i++) { for(int j = i+1; i < sums.length; j++) { if(sums[i]==sums[j]) { return false; } } } return true; }

Part A: arraySum Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.Notes: Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. This question involves reasoning about one-dimensional and two-dimensional arrays of integers. You will write three static methods, all of which are in a single enclosing class, named DiverseArray (not shown). The first method returns the sum of the values of a one-dimensional array; the second method returns an array that represents the sums of the rows of a two-dimensional array; and the third method analyzes row sums. (a) Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum. Complete method arraySum below. / * * Returns the sum of the entries in the one-dimensional array arr. * / public static int arraySum (int [ ] arr) (b) Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.For example, if mat1 is the array represented by the following table, the call rowSums(mat1) returns the array {16, 32, 28, 20}. Assume that arraySum works as specified, regardless of what you wrote in part (a). You must use arraySum appropriately to receive full credit. Complete method rowSums below. / * * Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. * / public static int [ ] rowSums(int [ ] [ ] arr2D) (c) A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false. Assume that arraySum and rowSums work as specified, regardless of what you wrote in parts (a) and(b). You must use rowSums appropriately to receive full credit.Complete method isDiverse below. / * * Returns true if all rows in arr2D have different row sums;* false otherwise. * /public static boolean isDiverse(int [ ] [ ] arr2D)

public static int arraySum(int[] arr) { int sum = 0; for(int elem : arr) { sum += elem; } return sum; }

Part B: rowSums Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.For example, if mat1 is the array represented by the following table, the call rowSums(mat1) returns the array {16, 32, 28, 20}. Assume that arraySum works as specified, regardless of what you wrote in part (a). You must use arraySum appropriately to receive full credit. Complete method rowSums below. / * * Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. * / public static int [ ] rowSums(int [ ] [ ] arr2D)

public static int[] rowSums(int[][] arr2D) { int[] sums = new int[arr2D.length]; int rowNum = 0; for(int[] row : arr2D) { sums[rowNum] = arraySum(row); rowNum++; } return sums; }

Part B: removeColumn Write the SparseArray method removeColumn. After removing a specified column from a sparsearray: All entries in the list entries with column indexes matching col are removed from the list. All entries in the list entries with column indexes greater than col are replaced by entries with column indexes that are decremented by one (moved one column to the left). The number of columns in the sparse array is adjusted to reflect the column removed. The sample object sparse from the beginning of the question is repeated for your convenience. The shaded entries in entries, below, correspond to the shaded column above. When sparse has the state shown above, the call sparse.removeColumn(1) could result insparse having the following values in its instance variables (since entries is in no particular order, itwould be equally valid to reverse the order of its two items). The shaded areas below show the changes.

public void removeColumn(int col) { int i = 0; while(i < entries.size()) { SparseArrayEntry e = entries.get(i); if(e.getCol() == col) { entries.remove(i); } else if(e.getCol() > col) { entries.set(i, new SparseArrayEntry(e.getRow(), e.getCol() - 1, e.getValue())); i++; } else { i++; } } numCols--; }

Question 2 (b) Write the UserName method setAvailableUserNames. The method removes from possibleNames all names that are found in usedNames. These represent user names that have already been assigned in the online system and are therefore unavailable. A helper method, isUsed, has been provided. The isUsed method searches for name in arr. The method returns true if an exact match is found and returns false otherwise. The example below shows the intended behavior of the setAvailableUserNames method. StatementStrings in possibleNames ​after statement executionString[] used = {"harta", "hartm", "harty"}; UserName person2 = new UserName("mary", "hart");"hartm", "hartma","hartmar", "hartmary"​person2.setAvailableUserNames(used);"hartma", "hartmar", "hartmary"​ Assume that the constructor works as specified, regardless of what you wrote in part (a). You must use isUsed appropriately to receive full credit. Complete the setAvailableUserNames method below. /** Removes strings from possibleNames that are found in usedNames as described in part (b). */ public void setAvailableUserNames(String[] usedNames)

public void setAvailableUserNames(String[] usedNames) { for(int i = 0; i < possibleNames.size(); i++) { if(isUsed(possibleNames.get(i), usedNames)) { possibleNames.remove(i); i--; } } }

(b) Write the StudentAssignments method updateGrade. The method replaces one and only one grade below 7070 in a given category, if any such grade exists and if the given category has more than five assignments with a grade of A. The identified grade is replaced with the value 7070. If more than one such assignment exists, the grade of any one of those assignments may be replaced. Assume that getNumberOfAs works as specified, regardless of what you wrote for part (a). You must use getNumberOfAs appropriately to receive full credit. Complete method updateGrade. /** Replaces a single assignment grade in a given category if the number of As in * the category is greater than 55 but at least one score is below 7070, as described in part (b) */ public void updateGrade(String cat)

public void updateGrade(String cat) { int aCount = getNumberOfAs(cat); if(aCount > 5) { for(Assignment a : assignmentList) { if(a.getGrade() < 70 && a.getCategory().equals(cat)) { a.setGrade(70); return; } } } }

Consider the following class definition. Each object of the class Employee will store the employee's name as name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate. public class Employee { private String name; private int wk_hours; private double pay_rate; public Employee(String nm, int hrs, double rt) { name = nm; wk_hours = hrs; pay_rate = rt; } public Employee(String nm, double rt) { name = nm; wk_hours = 20; pay_rate = rt; } } Which of the following code segments, found in a class other than Employee, could be used to correctly create an Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour? I. Employee e1 = new Employee("Lili", 20, 18.5); II. Employee e2 = new Employee("Steve", 18.5); III. Employee e3 = new Employee("Carol", 20);

C. I and II only

Consider the following method. public double secret(int x, double y) { return x / 2.0; } Which of the following lines of code, if located in a method in the same class as secret, will compile without error?

C. double result = secret(4, 4.0);

Consider the following code segment in which the int variables a and b have been properly declared and initialized. if (a < b) { a++; } else if (b < a) { b++; } else { a++; b++; } Which of the following code segments is equivalent to the code segment above?

E. if (a == b) { a++; b++; } else if (a < b) { a++; } else { b++; }

Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea". I. if (str.indexOf("pea") >= 0) { System.out.println("pea"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } II. if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pea") >= 0) { System.out.println("pea"); } Which of the following best describes the output produced by code segment I and code segment II?

E. Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a-z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment. fading trailing batting Write the code segment as described above. The code segment must use an enhanced for loop to earn full credit.

for (String str : words) { if(str.substring(str.length - 3).equals("ing")) { System.out.println(str); } }


Conjuntos de estudio relacionados

Lecture Exam 3 Thermoregulation/Hyperthermia/Hypothermia QARs

View Set

Unit 4: HR & Succession Planning

View Set

International Business Chapter 5

View Set

Rutgers supply chain final exam sample questions

View Set

AGRICULTURE HSC mid course revision

View Set

Personal Financial Literacy - Chapter 11

View Set