AP Computer Science A

Ace your homework & exams now with Quizwiz!

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

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

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 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");

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();

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); }

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); }

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() */

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

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

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.

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)

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

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

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

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

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

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 */ }

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

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

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

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

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

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

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.

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 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);

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 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; }

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

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

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

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

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

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

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

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]

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

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 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();

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();

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");

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));

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 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());

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 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; } } }


Related study sets

ACT study guide Math: Linear Inequalities with One Variable

View Set

Pennsylvania Public Adjuster Examination--Series 16-19 Set 2

View Set

Service Response Logistics (Chapter 12)

View Set

OP3207 - Scientific manuscripts and literature reviews

View Set

Culture and Social Structure Section Unit 3 Review Guide

View Set

The Hindenburg Reading Passage, ***TEAS READING, ***TEAS SCIENCE, Teas Review, Reading teas version 6, The Titanic Reading Passage, Bumblebees Reading passage, Teas Test Reading, TEAS 6th Edition (Reading), Travel Reading Passage Vocabulary, Teas Exa...

View Set

BRM Chapter 1: Research problems and questions and how they relate to debates in Research Methods

View Set

Anthro Final-Origin of Cities and States

View Set