cómp

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

8.23 Consider this class: public class Person { private String name; public Person(String firstName, String lastName){ name = lastName + ", " + firstName; } . . . } If an object is constructed as Person harry = new Person("Harry", "Morgan"); what is its name instance variable?

"Morgan, Harry"

8.18 Consider a class Grade that represents a letter grade, such as A+ or B. Give two different sets of instance variables that can be used for implementing the Grade class.

(1) String letterGrade; // "A+", "B" (2) double numberGrade; // 4.3, 3.0

8.16 Consider a class Time that represents a point in time, such as 9 a.m. or 3:30 p.m. Give two sets of instance variables that can be used for implementing the Time class. (Hint for the second set: Military time.)

(1) int hours; // Between 1 and 12 int minutes; // Between 0 and 59 boolean pm; // True for p.m., false for a.m. (2) int hours; // Military time, between 0 and 23 int minutes; // Between 0 and 59 (3) int totalMinutes // Between 0 and 60 * 24 - 1

8.27 Which constructors should be supplied in the Item class so that each of the following declarations compiles? a. Item item2 = new Item("Corn flakes"); b. Item item3 = new Item(3.95); c. Item item4 = new Item("Corn flakes", 3.95); d. Item item1 = new Item(); e. Item item5;

(a) Item(String) (b) Item(double) (c) Item(String, double) (d) Item() (e) No constructor has been called.

8.19 What are the values of register1.itemCount, register1.totalPrice, register2.itemCount, and register2.totalPrice after these statements? CashRegister register1 = new CashRegister(); register1.addItem(0.90); register1.addItem(0.95); CashRegister register2 = new CashRegister(); register2.addItem(1.90);

2 1.85 1 1.90

8.9 public class CashRegister{ private double saleTotal; public void addItem(double price) ... public double getTotal() ... ... What does the following code segment print? CashRegister reg = new CashRegister(); reg.clear(); reg.addItem(0.95); reg.addItem(0.95); System.out.println(reg.getCount() + " " + reg.getTotal());

2 1.90

6.2 Assume the array primes has been initialized as follows: int[] primes = { 2, 3, 5, 7, 11 }; What does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }

2, 3, 5, 3, 2

6.3 Assume the array primes has been initialized as follows: int[] primes = { 2, 3, 5, 7, 11 }; What does it contain after executing the following loop? for (int i = 0; i < 5; i++) { primes[i]++; }

3, 4, 6, 8, 12

8.25 public class CashRegister{ private double saleTotal; private int itemCount; public void addItem(double price) ... public double getTotal() ... ... What happens if you supply no constructor for the CashRegister class?

A constructor is generated that sets both instance variables to zero.

8.13 Is the nextInt method of the Scanner class an accessor or a mutator?

A mutator. Getting the next number removes it from the input, thereby modifying it. Not convinced? Consider what happens if you call the nextInt method twice. You will usually get two different numbers. But if you call an accessor twice on an object (without a mutation between the two calls), you are sure to get the same result.

Which statement calls a constructor with no construction parameters? A. Circle c = new Circle(); B. Circle c = new Circle; C. A call to a constructor must have construction parameters. D. Circle c = Circle()

A. Circle c = new Circle();

Which statements are true about array references? I. Assigning an array reference to another creates a second copy of the array. II. An array reference specifies the location of an array. III. Two array references can reference the same array. A. II and III only B. III only C. I only D. II only

A. II and III only An array reference specifies the location of an array. Two array references can reference the same array.

Consider the following code snippet: int[][] arr = { { 13, 23, 33 }, { 14, 24, 34 } }; Identify the appropriate statement to display the value 24 from the given array. A. System.out.println(arr[1][1]); B. System.out.println(arr[2][1]); C. System.out.println(arr[1][2]); D. System.out.println(arr[2][2]);

A. System.out.println(arr[1][1]);

Consider the following code snippet: int val = arr[0][2]; Which value of arr is stored in the val variable? A. The value in the first row and the third column B. The value in the first row and the first column C. The value in the third row and the second column D. The value in the first row and the second column

A. The value in the first row and the third column

What is the output of the following code snippet? public static void main(String[] args){ String[] arr = { "aaa", "bbb", "ccc" }; mystery(arr); System.out.println(arr[0] + " " + arr.length); } public static void mystery(String[] arr){ arr = new String[5]; arr[0] = "ddd"; } A. aaa 3 B. aaa 5 C. ddd 5 D. ddd 3

A. aaa 3

Consider the following code snippet: public int getCoinValue(String coinName) { . . . } Which of the following statements is correct? A. coinName is an explicit parameter. B. coinName is an instance variable. C. coinName is the object on which this method is invoked. D. coinName is an implicit parameter.

A. coinName is an explicit parameter.

Which of the following lists the correct order of items in an instance method declaration? A. modifiers, a return type, a method name, and a list of the parameters (if any) B. modifiers, the type of the instance variable, and the name of the instance variable C. the return type, the name of the method, and a list of the parameters (if any) D. the type of the instance variable, modifiers, and a list of the parameters (if any)

A. modifiers, a return type, a method name, and a list of the parameters (if any)

8.3 Describe a way in which a String object might store its characters.

As a char array.

Consider the following code snippet. What does the array contain at the end of the program? public static fillWithRandomNumbers(double[] values){ double[] numbers = new double[values.length]; for (int i = 0; i < numbers.length; i++){ numbers[i] = Math.random(); } values = numbers; } public static void main(String[] args){ double[] num = new double[20]; fillWithRandomNumbers(num); } A. 20 random numbers B. 20 zeros because array num is not changed by method C. Array index bound error D. Undefined data due to compilation error

B. 20 zeros because array num is not changed by method

What is the output of the code snippet below? int[][] arr = { { 1, 2, 3, 0 }, { 4, 5, 6, 0 }, { 0, 0, 0, 0 } }; int val = arr[1][2] + arr[1][3]; System.out.println(val); A. 9 B. 6 C. 5 D. 7

B. 6

Which of the following statements about constructors is NOT correct? A. A constructor must have the same name as the class name. B. A call to a constructor must always have construction parameters. C. A constructor initializes the instance variables of an object. D. A class can have more than one constructor.

B. A call to a constructor must always have construction parameters.

You have created a Motorcycle class which has a constructor with no parameters. Which of the following statements will construct an object of this class? A. myBike.new(Motorcycle); B. Motorcycle myBike = new Motorcycle(); C. Motorcycle myBike; D. Motorcycle.new(myBike);

B. Motorcycle myBike = new Motorcycle();

Which one of the following statements is correct for displaying the value in the third row and the fourth column of a twodimensional 5 by 6 array? A. System.out.println(arr[4][3]); B. System.out.println(arr[2][3]); C. System.out.println(arr[3][2]); D. System.out.println(arr[3][4]);

B. System.out.println(arr[2][3]);

A method in a class that returns information about an object but does not change the object is called a/an ____ method. A. constructor B. accessor C. mutator D. void

B. accessor

Which one of the following statements is a valid initialization of an array named somearray of ten elements? A. int somearray[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; B. int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; C. int somearray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; D. int[10] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

B. int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Which of the following declares a sideLength instance variable for a Square class that stores an integer value? A. public int sideLength; B. private int sideLength; C. private integer sideLength; D. public integer sideLength;

B. private int sideLength;

Another name for linear search is ____ search. A. random B. sequential C. sorted D. binary

B. sequential

Consider the following code snippet: public class Vehicle { . . . public void setVehicleAttributes(String attributes) {. . . } public String getVehicleAtrributes() {. . . } public String getModelName() {. . . } } Assuming that the names of the methods reflect their action, which of the following statements about this class is correct? A. setVehicleAttributes is an accessor method. B. setVehicleAttributes is a mutator method. C. getModelName is a mutator method. D. getVehicleAttributes is a mutator method.

B. setVehicleAttributes is a mutator method.

A constructor is invoked when ___ to create an object. A. the class keyword is used B. the new keyword is used C. the class is defined as public D. the class is defined as private

B. the new keyword is used

Fill in the blank for this algorithm for computing the average of values in a data array, assuming the array is not empty. double total = 0; for (int i = 0; i < element.length; i++){ total = total + element[i]; } double average = ____________________; A. total / data.length - 1 B. total / data.length C. total / data.length() D. total / data.length() - 1

B. total / data.length

Given the following class definition, which of the following are considered part of the class's public interface? public class CashRegister { public static final double DIME_VALUE = 0.1; private static int objectCounter; public void updateDimes(int dimes) {. . .} private boolean updateCounter(int counter) {. . .} } A. DIME_VALUE and objectCounter B. objectCounter and updateCounter C. DIME_VALUE and updateDimes D. updateDimes and updateCounter

C. DIME_VALUE and updateDimes

Why is the use of physical objects helpful in algorithm design? A. It simulates the way the computer actually implements the algorithm B. Because the constraints on physical things are the same as the constraints on bits and bytes C. Many people feel it is less intimidating than drawing diagrams D. It is more abstract than using a pencil and paper

C. Many people feel it is less intimidating than drawing diagrams

What is the purpose of this algorithm? for (int i = 0; i < names.length; i++){ if (i > 0){ System.out.print("; "); } System.out.print(names[i]); } A. Prints out the names in an array separated by commas. B. Appends a semicolon to the end of each name in an array and prints it. C. Prints out the names in an array separated by semicolons. D. Appends a comma to the end of each name in an array and prints it.

C. Prints out the names in an array separated by semicolons.

The partial linear search method below is designed to search an array of String objects. Select the expression that would be needed to complete the method. public static int search(String[] a, String item) { for(int i = 0; i < a.length; i++) { if ( ____________________________ ) { return i; } return -1; } } A. a[i] == item B. a[i].compareTo(item) C. a[i].equals(item) D. a[i].indexOf(item)

C. a[i].equals(item)

An instance variable declaration consists of ____. A. the type of the instance variable, an access specifier, a list of the parameters (if any), and the body of the method B. an access specifier, a list of the parameters (if any), and the body of the method C. an access specifier, the type of the instance variable, and the name of the instance variable D. the return type, the name of the method, and a list of the parameters (if any)

C. an access specifier, the type of the instance variable, and the name of the instance variable

Each object of a class has a separate copy of each ___. A. constructor B. class C. instance variable D. method

C. instance variable

Consider the following code snippet: int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } }; int val = arr[0][2] + arr[1][2]; System.out.println(val); What is the output of the given code snippet on execution? A. 7 B. 5 C. 10 D. 9

D. 9

Which of the following statements about classes is correct? A. Class is another name for a method. B. A class is an object that can be manipulated by a program. C. A class can contain only methods. D. A class describes a set of objects with the same behavior.

D. A class describes a set of objects with the same behavior.

What is the purpose of this algorithm? double total = 0; for (int i = 0; i < element.length; i++){ total = total + element; } A. Counting matches. B. Locating an element. C. Finding a value. D. Computing the sum.

D. Computing the sum.

Which statements about array algorithms are true? I. The array algorithms are building blocks for many programs that process arrays. II. Java contains ready-made array algorithms for every problem situation. III. It is inefficient to make multiple passes through an array if you can do everything in one pass. A. I, II, and III B. I and II only C. II and III only D. I and III only

D. I and III only

Consider the telephone book as a physical object that can help understand algorithms. What kind of algorithm might be visualized using it? A. Monte Carlo methods B. Finding the maximum C. Sorting D. Searching

D. Searching

Consider the following code snippet: public class Coin { private String coinName; public String getCoinValue() { . . . } } Which of the following statements is correct? A. The getCoinValue method can be accessed only by methods of another class. B. The getCoinValue method can be accessed only by methods of the Coin class. C. The getCoinValue method cannot be accessed at all. D. The getCoinValue method can be accessed by any user of a Coin object.

D. The getCoinValue method can be accessed by any user of a Coin object.

The process of hiding object data and providing methods for data access is called ____. A. initialization B. implementation C. documentation D. encapsulation

D. encapsulation

Which code correctly swaps elements in a non-empty data array for valid positions j and k? A. data[j] = data[k]; data[k] = data[j]; B. int t = data[j]; data[k] = t; data[j] = data[k]; C. data[k] = data[j]; data[j] = data[k]; D. int t = data[j]; data[j] = data[k]; data[k] = t;

D. int t = data[j]; data[j] = data[k]; data[k] = t;

Which one of the following is the correct header for a method named arrMeth that is called like this: // intArray is an integer array of size 3 arrMeth(intArray); A. public static void arrMeth(int ar[]) B. public static void arrMeth(ar int[]) C. public static void arrMeth(int ar) D. public static void arrMeth(int[] ar)

D. public static void arrMeth(int[] ar)

6.31 Consider the task of rearranging all elements in an array so that the even numbers come first. Otherwise, the order doesn't matter. For example, the array 1 4 14 2 1 3 5 6 23 could be rearranged to 4 2 14 6 1 5 3 23 1 Using coins and paperclips, discover an algorithm that solves this task by swapping elements, then describe it in pseudocode.

Here is one solution. The basic idea is to move all odd elements to the end. Put one paper clip at the beginning of the array and one at the end. If the element at the first paper clip is odd, swap it with the one at the other paper clip and move that paper clip to the left. Otherwise, move the first paper clip to the right. Stop when the two paper clips meet. Here is the pseudocode: i = 0 j = size - 1 While i < j If a[i] is odd Swap elements at positions i and j. j-- Else i++

6.32 Discover an algorithm for the task of Self Check 31 that uses removal and insertion of elements instead of swapping.

Here is one solution. The idea is to remove all odd elements and move them to the end. The trick is to know when to stop. Nothing is gained by moving odd elements into the area that already contains moved elements, so we want to mark that area with another paper clip. i = 0 moved = size While i < moved If a[i] is odd Remove the element at position i. Add the removed element to the end. moved-

6.14 Consider the algorithm to find the largest element in an array. Why don't we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++){ if (values[i] > largest){ largest = values[i]; } }

If all elements of values are negative, then the result is incorrectly computed as 0.

6.16 What is wrong with these statements for printing an array with separators? System.out.print(values[0]); for (int i = 1; i < values.length; i++) { System.out.print(", " + values[i]); }

If the array has no elements, then the program terminates with an exception.

6.17 When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }

If there is a match, then pos is incremented before the loop exits.

6.30 Take out some coins and simulate the following pseudocode, using two paper clips to indicate the positions for i and j. i = 0 j = size - 1 While i < j Swap elements at positions i and j. i++ j- What does the algorithm do?

It reverses the elements in the array.

8.1 Is the method call "Hello, World".println() legal? Why or why not?

No--the object "Hello, World" belongs to the String class, and the String class has no println method.

8.7 Suppose another programmer has used the original Counter class. What changes does that programmer have to make in order to use the modified class?

None--the public interface has not changed.

8.4 Suppose the providers of your Java compiler decide to change the way that a String object stores its characters, and they update the String method implementations accordingly. Which parts of your code do you need to change when you get the new compiler?

None. The methods will have the same effect, and your code could not have manipulated String objects in any other way.

8.22 Consider the length method of the String class. How many parameters does it have, and what are their types?

One parameter: the implicit parameter of type String. The method has no explicit parameters. int length = stringName.length();

6.5 Declare an array called words that can hold ten elements of type String. Answer

String[] words = new String[10];

6.6 Declare an array containing two strings, "Yes", and "No".

String[] words = { "Yes", "No" };

6.36 Declare a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings "x", "o", and " ".

String[][] board = new String[3][3];

8.15 What is wrong with this code segment? CashRegister register2 = new CashRegister(); register2.clear(); register2.addItem(0.95); System.out.println(register2.totalPrice);

The code tries to access a private instance variable.

6.22 Consider the following method that reverses an array: public static int[] reverse(int[] values) { int[] result = new int[values.length]; for (int i = 0; i < values.length; i++) { result[i] = values[values.length - 1 - i]; } return result; } Suppose the reverse method is called with an array scores that contains the numbers 1, 4, and 9. What is the contents of scores after the method call?

The contents of scores is unchanged. The reverse method returns a new array with the reversed numbers.

6.21 Describe the purpose of the following method: public static int[] mystery(int length, int n){ int[] result = new int[length]; for (int i = 0; i < result.length; i++) { result[i] = (int) (n * Math.random()); } return result; }

The method returns an array whose length is given in the first argument. The array is filled with random integers between 0 and n - 1.

6.29 Walk through the algorithm for swapping the first half of the coins with the second half of the coins, using two paper clips to indicate the positions for i and j. Explain why there are no bounds errors in the pseudocode.

The paperclip for i assumes positions 0, 1, 2, 3. When i is incremented to 4, the condition i < size / 2 becomes false, and the loop ends. Similarly, the paperclip for j assumes positions 4, 5, 6, 7, which are the valid positions for the second half of the array.

8.10 public class CashRegister{ private double saleTotal; public void addItem(double price) ... public double getTotal() ... ... What is wrong with the following code segment? CashRegister reg = new CashRegister(); reg.clear(); reg.addItem(0.95); System.out.println(reg.getAmountDue());

There is no method named getAmountDue.

8.17 Suppose the implementor of the Time class changes from one implementation strategy to another, keeping the public interface unchanged. What do the programmers who use the Time class need to do?

They need not change their programs at all because the public interface has not changed. They need to recompile with the new version of the Time class.

6.18 When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; }

This loop sets all elements to values[pos].

8.21 Consider the substring method of the String class. How many parameters does it have, and what are their types?

Three parameters: two explicit parameters of type int, and one implicit parameter of type String. String substr2 = s1.substring(5,10);

8.2 When using a String object, you do not know how it stores its characters. How can you access them?

Through the substring and charAt methods.

6.26 How can you print the number of positive and negative values in a given array, using one or more of the common loop algorithms?

Use the algorithm for counting matches twice, once for counting the positive values and once for counting the negative values.

6.28 Consider the following algorithm for collecting all matches in an array: int matchesSize = 0; for (int i = 0; i < values.length; i++) { if (values[i] fulfills the condition) { matches[matchesSize] = values[i]; matchesSize++; } } How can this algorithm help you with print the positive elements of an array?

Use the algorithm to collect all positive elements in an array, then use the algorithm to print the array of matches.

6.33 Consider the algorithm that finds the largest element in a sequence of inputs—not the largest element in an array. Why is this algorithm better visualized by picking playing cards from a deck rather than arranging toy soldiers in a sequence?

When you read inputs, you get to see values one at a time, and you can't peek ahead. Picking cards one at a time from a deck of cards simulates this process better than looking at a sequence of items, all of which are revealed.

8.8 Suppose you use a class Clock with private instance variables hours and minutes. How can you access these variables in your program?

You cannot access the instance variables directly. You must use the methods provided by the Clock class.

6.27 How can you print all positive values in an array, separated by commas?

You need to modify the algorithm for printing an array contents boolean first = true; for (int i = 0; i < values.length; i++) { if (values[i] > 0)) { if (first) { first = false; } else { System.out.print(", "); } } System.out.print(values[i]); } Note that you can no longer use i > 0 as the criterion for printing a separator.

6.38 Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board? String[][] board = new String[3][3];

board[0][0], board[1][1], board[2][2]

6.37 Write an assignment statement to place an "x" in the upper-right corner of the tic-tactoe board. String[][] board = new String[3][3];

board[0][2] = "x";

6.15 When printing separators, we skipped the separator before the initial element. Rewrite the loop so that the separator is printed after each element, except for the last element.

for (int i = 0; i < values.length; i++){ System.out.print(values[i]); if (i < values.length - 1){ System.out.print(" | "); } } Now you know why we set up the loop the other way.

6.13 Write a loop that counts how many elements in an array are equal to zero.

int count = 0; for (double x : values) { if (x == 0) { count++; } }

6.19 How do you call the squares method to compute the first five squares and store the result in an array numbers?

int[] numbers = squares(5);

6.1 Declare an array of integers containing the first five prime numbers.

int[] primes = { 2, 3, 5, 7, 11 };

8.12 Name two accessor methods of the String class.

length, substring. In fact, all methods of the String class are accessors.

8.26 Consider the following class: public class Item { private String description; private double price; public Item() { . . . } // Additional methods omitted } Provide an implementation for the constructor.

public Item() { price = 0; description = ""; } The price instance variable need not be initialized because it is set to zero by default, but it is clearer to initialize it explicitly.

8.24 Provide an implementation for a Person constructor so that after the call Person p = new Person(); the name instance variable of p is "unknown".

public Person() { name = "unknown"; }

8.20 public class CashRegister{ private double saleTotal; public void addItem(double price) ... public double getTotal() ... ... Implement a method getDollars of the CashRegister class that yields the amount of the total sale as a dollar value without the cents.

public int getDollars() { int dollars = (int) totalPrice; // Truncates cents return dollars; }

8.11 public class CashRegister{ private double saleTotal; public void addItem(double price) ... public double getTotal() ... ... Declare a method getDollars of the CashRegister class that yields the amount of the total sale as a dollar value without the cents.

public int getDollars();

8.6 Consider a change to the implementation of the counter. Instead of using an integer counter, we use a string of | characters to keep track of the clicks, just like a human might do. public class Counter { private String strokes = ""; public void count() { strokes = strokes + "|"; } . . . } How do you implement the getValue method with this data representation?

public int getValue() { return strokes.length(); }

6.20 Write a method fill that fills all elements of an array of integers with a given value. For example, the call fill(scores, 10) should fill all elements of the array scores with the value 10.

public static void fill(int[] values, int value) { for (int i = 0; i < values.length; i++) { values[i] = value; } }

8.5 Supply the body of a method public void reset() that resets the counter, value, back to zero.

public void reset() { value = 0; }

6.4 Given the declaration int[] values = new int[10] write statements to put the integer 10 into the elements of the array values with the lowest and the highest valid index.

values[0] = 10; values[9] = 10; or better: values[values.length - 1] = 10;


Conjuntos de estudio relacionados

Pharmacology Chapter 54: Drugs Acting on the Upper Respiratory Tract

View Set