Вы находитесь на странице: 1из 30

APPENDIX

Answers to Odd-Numbered Review Questions

Chapter 1
Multiple Choice 1. 3. 5. 7. 9. 11. 13. b a b c a a b

Find the Error 1. The algorithm performs the math operation at the wrong time. It multiplies width by length before getting values for those variables.

Algorithm Workbench 1. Display What is the customers maximum amount of credit? Input maxCredit. Display What is the amount of credit used by the customer? Input creditUsed. availableCredit = maxCredit creditUsed. Display availableCredit. Display What is the accounts starting balance? Input startingBalance. Display What is the total amount of the deposits made? Input deposits.

3.

L-1

L-2

Appendix L

Answers to Odd-Numbered Review Questions

Display What is the total amount of the withdrawals made? Input withdrawals. Display What is the monthly interest rate? Input interestRate. balance = startingBalance + deposits withdrawals. interest = balance * interestRate. balance = balance + interest. Display balance. Predict the Result 1. 7

Short Answer 1. Main memory, or RAM, holds the sequences of instructions in the programs that are running and the data those programs are using. Main memory, or RAM, is usually volatile. Secondary storage is a type of memory that can hold data for long periods of timeeven when there is no power to the computer. An operating system is a set of programs that manages the computers hardware devices and controls their processes. Windows and UNIX are examples of operating systems. Application software refers to programs that make the computer useful to the user. These programs solve specific problems or perform general operations that satisfy the needs of the user. Word processing, spreadsheet, and database packages are all examples of application software. Because machine language programs are streams of binary numbers, and highlevel language programs are made up of words. Syntax errors are mistakes that the programmer has made that violate the rules of the programming language. Logical errors are mistakes that cause the program to produce erroneous results. A program that translates source code into executable code. Because the browser executes them in a restricted environment. Machine language code is executed directly by the CPU. Byte code is executed by the JVM. Object-oriented programming The objects methods. No
javac LabAssignment.java

3.

5. 7.

9. 11. 13. 15. 17. 19. 21.

Chapter 2

L-3

Chapter 2
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. c a a, c, and d c a b a a True True False

Predict the Output 1. 3.


0 100 I am the incrediblecomputing machine and I will amaze you. 23 1

5.

Find the Error The comment symbols in the first line are reversed. They should be /* and */. The word class is missing in the second line. It should read public class MyProgram. The main header should not be terminated with a semicolon. The fifth line should have a left brace, not a right brace. The first four lines inside the main method are missing their semicolons. The comment in the first line inside the main method should begin with forward slashes (//), not backward slashes.

L-4

Appendix L

Answers to Odd-Numbered Review Questions

The last line inside the main method, a call to println, uses a string literal, but the literal is enclosed in single quotes. It should be enclosed in double quotes, like this: "The value of c is". The last line inside the main method passes C to println, but it should pass c (lowercase). The class is missing its closing brace.

Algorithm Workbench 1. 3.
double temp, weight, age;

a) b) c) d) e) f)

b a b a c c

= = = = = =

a + 2; b * 4; a / 3.14; b 8; K; 66;

5.

a) 3.287E6 b) -9.7865E12 c) 7.65491E-3


int speed, time, distance; speed = 20; time = 10; distance = speed * time; System.out.println(distance); double income; // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Ask the user to enter his or her desired income System.out.print("Enter your desired annual income: "); income = keyboard.nextDouble(); total = (float)number;

7.

9.

11.

Short Answer 1. 3. 5. 7. Multi-line style A self-documenting program is written in such a way that you get an understanding of what the program is doing just by reading its code. The print and println methods are members of the out object. The out object is a member of the System class. The System class is part of the Java API. You should always choose names for your variables that give an indication of what they are used for. The rather nondescript name, x, gives no clue as to what the variables purpose is.

Chapter 3

L-5

9.

In both cases you are storing a value in a variable. An assignment statement can appear anywhere in a program. An initialization, however, is part of a variable declaration. Programming style refers to the way a programmer uses spaces, indentations, blank lines, and punctuation characters to visually arrange a programs source code. An inconsistent programming style can create confusion for a person reading the code.
javadoc SalesAverage.java

11.

13.

Chapter 3
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. b a c a a a c c True True True

Find the Error 1. 3. 5. Each if clause is prematurely terminated by a semicolon. The conditionally executed blocks of code should be enclosed in braces. The ! operator is only applied to the variable x, not the expression. The code should read:
if (!(x > 20))

7. 9.

The statement should use the || operator instead of the && operator. The equalsIgnoreCase method should be used instead of the equals method.

Algorithm Workbench 1.
if (y == 0) x = 100;

L-6

Appendix L

Answers to Odd-Numbered Review Questions

3.

if (sales < 10000) commission = .10; else if (sales <= 15000) commission = .15; else commission = .20; if (amount1 > 10) { if (amount2 < 100) { if (amount1 > amount2) { System.out.println(amount1); } else { System.out.println(amount2); } } } if (temperature >= -50 && temperature <= 150) System.out.printn("The number is valid."); if (title1.compareTo(title2) < 0) System.out.println(title1 + " " + title2); else System.out.println(title2 + " " + title1);

5.

7. 9.

11. 13.

C, A, B 0.00

Short Answer 1. 3. Conditionally executed code is executed only under a condition, such as an expression being true. By indenting the conditionally executed statements, you are causing them to stand out visually. This is so you can tell at a glance what part of the program the if statement executes. A flag is a boolean variable that signals when some condition exists in the program. When the flag variable is set to false, it indicates the condition does not yet exist. When the flag variable is set to true, it means the condition does exist. It takes two boolean expressions as operands and creates a boolean expression that is true only when both subexpressions are true. They determine whether a specific relationship exists between two values. The relationships are greater-than, less-than, equal-to, not equal-to, greater-than or equal-to, and less-than or equal-to.

5.

7. 9.

Chapter 4

L-7

Chapter 4
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. 23. 25. a c a b c a a d d True False False True

Find the Error 1. 3. The conditionally executed statements should be enclosed in a set of braces. Also, the again variable should be initialized with either y or Y. The expression being tested by the do-while loop should be choice == 1. Also, the do-while loop must be terminated by a semicolon.

Algorithm Workbench 1.
Scanner keyboard = new Scanner(System.in); int product = 0, num; while (product < 100) { num = keyboard.nextInt(); product = num * 10; }

3.

The following code simply prints the numbers, separated by spaces.


for (int x = 0; x <= 1000; x += 10) System.out.print(x + " ");

The following code prints the numbers separated by commas.


for (int x = 0; x <= 1000; x += 10) { if (x < 1000)

L-8

Appendix L

Answers to Odd-Numbered Review Questions System.out.print(x + ", "); else System.out.print(x); }

5.

double total = 0; for (int num = 1, denom = 30; num <= 30; num++, denom--) total += num / denom; Scanner keyboard = new Scanner(System.in); int x; do { System.out.print("Enter a number: "); x = keyboard.nextInt(); } while (x > 0); for (int count = 0; count > 50; count++) System.out.println("count is " + count); int number; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the range " + "of 1 through 4: "); number = keyboard.nextInt(); while (number < 1 || number > 4) { System.out.print("Invalid number. Enter a " + "number in the range " + "of 1 through 4: "); number = keyboard.nextInt(); } PrintWriter outFile = new PrintWriter("NumberList.txt"); for (int i = 1; i <= 100; i++) outFile.println(i); outFile.close(); File file = new File("NumberList.txt"); Scanner inFile = new Scanner(file); String input; int number, total = 0; while (inFile.hasNext()) { input = inFile.nextLine(); number = Integer.parseInt(input); total += number; } System.out.println("The total is " + total); inFile.close();

7.

9. 11.

13.

15.

Chapter 5

L-9

Short Answer 1. In postfix mode the operator is placed after the operand. In prefix mode the operator is placed before the variable operand. Postfix mode causes the increment or decrement operation to happen after the value of the variable is used in the expression. Prefix mode causes the increment or decrement to happen first. A pretest loop tests its test expression before each iteration. A posttest loop tests its test expression after each iteration. The while loop is a pretest loop and the do-while loop is a posttest loop. The do-while loop. An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total. There are many possible examples. A program that asks the user to enter a businesss daily sales for a number of days, and then displays the total sales is one example. Sometimes the user has a list of input values that is very long, and doesnt know the number of items there are. When the sentinel value is entered, it signals the end of the list, and the user doesnt have to count the number of items in the list. There are many possible examples. One example is a program that asks for the average temperature for each month, for a period of five years. The outer loop would iterate once for each year and the inner loop would iterate once for each month. Closing a file writes any unsaved data remaining in the file buffer. After the println method writes its data, it writes a newline character. The print method does not write the newline character. The file does not exist. You create an instance of the FileWriter class to open the file. You pass the name of the file (a string) as the constructors first argument, and the boolean value true as the second argument. Then, when you create an instance of the PrintWriter class, you pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The file will not be erased if it already exists and new data will be written to the end of the file.

3. 5. 7. 9.

11.

13.

15.

17. 19. 21. 23.

Chapter 5
Multiple Choice and True/False 1. 3. 5. b a b

L-10

Appendix L

Answers to Odd-Numbered Review Questions

7. 9. 11. 13. 15. 17. 19.

b c True False True False False

Find the Error 1. 3. The header should not be terminated with a semicolon. The method should have a return statement that returns a double value.

Algorithm Workbench 1. 3. 5. 7.
doSomething(25);

The value 3 will be stored in a, 2 will be stored in b, and 1 will be stored in c.


result = cube(4); public static double timesTen(double num) { return num * 10.0; }

Short Answer 1. 3. A large complex problem is broken down into smaller manageable pieces. Each smaller piece of the problem is then solved. An argument is a value that is passed into a method when the method is called. A parameter variable is a variable that is declared in the method header, and receives the value of an argument when the method is called. When an argument is passed to a method, only a copy of the argument is passed. The method cannot access the actual argument.

5.

Chapter 6
Multiple Choice and True/False 1. 3. 5. 7. 9. a d b d b

Chapter 6

L-11

11. 13. 15. 17. 19.

c b True False False

Find the Error 1. 3. 5. The constructor cannot have a return type, not even void. The parentheses are missing. The statement should read:
Rectangle box = new Rectangle();

The square methods must have different parameter lists. Both accept an int.

Algorithm Workbench 1. a) UML diagram:

Pet - name : String - animal : String - age : int + setName(n : String) : void + setAnimal(a : String) : void + setAge(a : int) : void + getName() : String + getAnimal() : String + getAge() : int
b) Class code:
public class Pet { private String name; private String animal; private int age; /** setName method @param n The pet's name. */ public void setName(String n) { name = n; }

// The pet's name // The type of animal // The pet's age

L-12

Appendix L

Answers to Odd-Numbered Review Questions /** setAnimal method @param a The type of animal. */ public void setAnimal(String a) { animal = a; } /** setAge method @param a The pet's age. */ public void setAge(int a) { age = a; } /** getName method @return The pet's name. */ public String getName() { return name; } /** getAnimal method @return The type of animal. */ public String getAnimal() { return animal; } /** getAge method @return The pet's age. */

Chapter 7 public int getAge() { return age; } }

L-13

3.

a) public Square()
{ sideLength = 0.0; } b) public Square(double s) { sideLength = s; }

Short Answer 1. A class is a collection of programming statements that specify the attributes and methods that a particular type of object may have. You should think of a class as a blueprint that describes an object. An instance of a class is an actual object that exists in memory. An accessor method is a method that gets a value from a classs field but does not change it. A mutator method is a method that stores a value in a field or in some other way changes the value of a field. Methods that are members of the same class. It looks in the current folder or directory for the file Customer.class. If that file does not exist, the compiler searches for the file Customer.java and compiles it. This creates the file Customer.class, which makes the Customer class available. The same procedure is followed when the compiler searches for the Account class. If you do not write a constructor for a class, Java automatically provides one. By their signatures, which includes the method name and the data types of the method parameters, in the order that they appear.

3.

5. 7.

9. 11.

Chapter 7
Multiple Choice and True/False 1. 3. 5. 7. c c d b

L-14

Appendix L

Answers to Odd-Numbered Review Questions

9. 11. 13. 15. 17. 19.

b a False True False False

Find the Error 1. 3. 5. The x is missing in the package name. The statement should read:
import javax.swing.*;

The arguments passed to the GridLayout constructor are reversed. This statement creates 10 rows and 5 columns. You do not create an instance of BorderFactory. Instead you call one of its static methods to create a Border object. The statement should read:
panel.setBorder(BorderFactory.createTitledBorder("Choices"));

Algorithm Workbench 1. 3. 5. 7. 9.
myWindow.setSize(500, 250); myWindow.setVisible(true); setLayout(new FlowLayout(FlowLayout.LEFT)); panel.add(button, BorderLayout.WEST); panel.setBorder(BorderFactory.createLineBorder(Color.blue, 2));

Short Answer 1. 3. The window is hidden from view, but the application does not end. Radio buttons are normally used to select one of several possible items. Because a mutually exclusive relationship usually exists between radio buttons, only one of the items may be selected. Check boxes, which may appear alone or in groups, allow the user to make yes/no or on/off selections. Because there is not usually a mutually exclusive relationship between check boxes, the user can select any number of them when they appear in a group.

Chapter 8
Multiple Choice and True/False 1. 3. 5. b b c

Chapter 8

L-15

7. 9. 11. 13. 15. 17. 19. 21. 23.

b d c a False True True False True

Find the Error 1. 3. 5. The size declarator cannot be negative. The loop uses the values 1 through 10 as subscripts. It should use 0 through 9. A subscript should be used with words, such as words[0].toUpperCase().

Algorithm Workbench 1. 3.
for (int i = 0; i < 20; i++) System.out.println(names[i]);

a) String[] scientists = {"Einstein", "Newton",


"Copernicus", "Kepler"};

b) for (int i = 0; i < scientists.length; i++)


System.out.println(scientists[i]); c) int total = 0; for (int i = 0; i < scientists.length; i++) total += scientists[i].length(); System.out.println("The total length is " + total);

5.

a) // Define the arrays.


int[] id = new int[10]; double[] weeklyPay = new double[10]; b) // Display each employees gross weekly pay. for (int i = 0; i < 10; i++) { System.out.println("The pay for employee " + id[i] + " is $" + weeklyPay[i]); }

7.

final int NUM_ROWS = 30; final int NUM_COLS = 10; int total = 0; double average; for (int row = 0; row < grades.length; row++)

L-16

Appendix L

Answers to Odd-Numbered Review Questions { for (int col = 0; col < grades[row].length; col++) { total += grades[row][col]; } } average = (double) total / (NUM_ROWS * NUM_COLS);

9.

double total = 0.0; // Accumulator // Sum the values in the array. for (int row = 0; row < 10; row++) { for (int col = 0; col < 20; col++) total += values[row][col]; } // Create an ArrayList. ArrayList<String> cars = new ArrayList<String>(); // Add three car names to the ArrayList. cars.add("Porsche"); cars.add("BMW"); cars.add("Jaguar"); // Display the contents of cars. for (String str : cars) System.out.println(str);

11.

Short Answer 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element in an array. a) 2 b) 14 c) 8 Because this statement merely makes array1 reference the same array that array2 references. Both variables will reference the same array. To copy the contents of array2 to array1, the contents of array2s individual elements will have to be assigned to the elements of array1. It will have to read all 10,000 elements to find the value stored in the last element.

3.

5.

7.

Chapter 9
Multiple Choice and True/False 1. 3. c a

Chapter 9

L-17

5. 7. 9. 11. 13. 15. 17.

b d c b False False True

Find the Error 1. The static method setValues cannot refer to the non-static fields x and y.

Algorithm Workbench 1. a) public String toString()


{ String str; str = "Radius: " + radius + " Area: " + getArea(); return str; } b) public boolean equals(Circle c) { boolean status; if (c.getRadius() == radius) status = true; else status = false; return status; } c) public boolean greaterThan(Circle c) { boolean status; if (c.getArea() > getArea()) status = true; else status = false; return status; }

3.

enum Pet { DOG, CAT, BIRD, HAMSTER }

Short Answer 1. 3. Access a non-static member. When a variable is passed as an argument, a copy of the variables contents is passed. The receiving method does not have access to the variable itself. When

L-18

Appendix L

Answers to Odd-Numbered Review Questions

an object is passed as an argument, a reference to the object (which is the objects address) is passed. This allows the receiving method to have access to the object. 5. 7. It means that an aggregate relationship exists. When an object of class B is a member of class A, it can be said that class A has a class B object. It is not advisable because it will allow access to the private fields. The exception to this is when the field is a String object. This is because String objects are immutable, meaning that they cannot be changed. a) Color b) Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE c) Color myColor = Color.BLUE; When there are no references to it.

9.

11.

Chapter 10
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. 23. c a a b d a d False False True True False

Find the Error 1. The valueOf method is static. It should be called like this:
str = String.valueOf(number);

3.

The very first character is at position 0, so the statement should read:


str.setCharAt(0, 'Z');

Algorithm Workbench 1.
if (Character.toUpperCase(choice) == 'Y')

or

Chapter 11 if (Character.toLowerCase(choice) == 'y')

L-19

3.

int total = 0; for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) total++; } public static boolean dotCom(String str) { boolean status; if (str.endsWith(".com")) status = true; else status = false; return status; } public static void upperT(StringBuilder str) { for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 't') str.setCharAt(i, 'T'); } } if (d <= Integer.MAX_VALUE) i = (int) d;

5.

7.

9.

Short Answer 1. 3. This will improve the programs efficiency by reducing the number of String objects that must be created and then removed by the garbage collector. Converts a number to a string.

Chapter 11
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. b d a c a a

L-20

Appendix L

Answers to Odd-Numbered Review Questions

13. 15. 17. 19. 21. 23. 25. 27. 29.

c c c True False False True True True

Find the Error 1. 3. The Car class header should use the word extends instead of expands. Because the Vehicle class does not have a default constructor or a no-arg constructor, the Car class constructor must call the Vehicle class constructor.

Algorithm Workbench 1. 3.
public class Poodle extends Dog public abstract class B { private int m; protected int n; public void setM(int value) { m = value; } public void setN(int value) { n = value; } public int getM() { return m; } public int getN() { return n; }

Chapter 11 public abstract double calc(); } public class D extends B { private double q; protected double r; public void setQ(double value) { q = value; } public void setR(double value) { r = value; } public double getQ() { return q; } public double getR() { return r; } public double calc() { return q * r; } }

L-21

5.

setValue(10);

or
super.setValue(10);

7.

public class Stereo extends SoundSystem implements CDPlayable, TunerPlayable, CassettePlayable

Short Answer 1. When an is a relationship exists between objects, it means that the specialized object has all of the characteristics of the general object, plus additional characteristics that make it special.

L-22

Appendix L

Answers to Odd-Numbered Review Questions

3. 5. 7.

Dog is the superclass and Pet is the subclass.

No. Overloading is when a method has the same name as one or more other methods, but a different parameter list. Although overloaded methods have the same name, they have different signatures. When a method overrides another method, however, they both have the same signature. At runtime. An abstract class is not instantiated itself, but serves as a superclass for other classes. The abstract class represents the generic or abstract form of all the classes that inherit from it.

9. 11.

Chapter 12
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. 23. b a b d c c d c True False True False

Find the Error 1. 3. The try block must appear first. The catch (Exception e) statement and its block should appear after the other catch blocks, because this is a more general exception than the others.

Algorithm Workbench 1. 3.
B D public static int arraySearch(int[] array, int value) throws Exception

Chapter 12 { int i; int element; boolean found; // Loop control variable // Element the value is found at // Flag indicating search results

L-23

// Element 0 is the starting point of the search. i = 0; // Store the default values element and found. element = -1; found = false; // Search the array. while (!found && i < array.length) { if (array[i] == value) { found = true; element = i; } i++; } if (element == -1) throw new Exception("Element not found."); else return element; }

5.

public class NegativeNumber extends Exception { /** No-arg constructor */ public NegativeNumber() { super("Error: Negative number"); } /** The following constructor accepts the number that caused the exception. @param n The number. */ public NegativeNumber(int n) { super("Error: Negative number: " + n); } }

L-24

Appendix L

Answers to Odd-Numbered Review Questions

7. 9. 11.

public int getValueFromFile() throws IOException, FileNotFoundException FileOutputStream fstream = new FileOutputStream("Configuration.dat"); FileOutputStream outStream = new FileOutputStream("ObjectData.dat"); ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream); objectOutputFile.writeObject(r);

Short Answer 1. 3. An exception object has been created in response to an error that has occurred. Control of the program is passed to the previous method in the call stack (that is, the method that called the offending method). If that method cannot handle the exception, then control is passed again, up the call stack, to the previous method. This continues until control reaches the main method. If the main method does not handle the exception, then the program is halted and the default exception handler handles the exception. The first statement after that try/catch construct. Any object that inherits from the Throwable class. Unchecked exceptions are those that inherit from the Error class or the RuntimeException class. You should not handle these exceptions because the conditions that cause them can rarely be dealt with within the program. All of the remaining exceptions (that is, those that do not inherit from Error or RuntimeException) are checked exceptions. These are the exceptions that you should handle in your program. All of the data stored in a text file is formatted as text. Even numeric data is converted to text when it is stored in a text file. You can view the data stored in a text file by opening it with a text editor, such as Notepad. In a binary file, data is not formatted as text. Subsequently, you cannot view a binary files contents with a text editor. When an object is serialized it is converted to a series of bytes which are written to a file. When the object is deserialized, the series of bytes are converted back into an object.

5. 7. 9.

11.

13.

Chapter 13
Multiple Choice and True/False 1. 3. 5. d b a

Chapter 13

L-25

7. 9. 11. 13. 15. 17. 19. 21. 23. 25. 27. 29. 31. 33. 35.

c b c a b a b a False False True True True False True

Find the Error 1. 3. 5. 7. The argument false should have been passed to the setEditable method. You should pass list as an argument to the JScrollPane constructor:
JScrollPane scrollPane = new JScrollPane(list);

The second statement should read:


label.setIcon(image);

The statement should read:


JTextArea textArea = new JTextArea (5, 20);

Algorithm Workbench 1. 3. 5. 7. 9.
JTextField textField = new JTextField(20); textField.setEditable(false); dayList.setVisibleRowCount(4); JScrollPane scrollPane = new JScrollPane(dayList); selectionIndex = myComboBox.getSelectedIndex(); ImageIcon image = new ImageIcon("picture.gif"); label.setIcon(image); JFileChooser fileChooser = new JFileChooser(); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION)

L-26

Appendix L

Answers to Odd-Numbered Review Questions { File selectedFile = fileChooser.getSelectedFile(); String filename = selectedFile.getPath(); }

11.

// Create an Open menu item. JMenuItem openItem = new JMenuItem("Open"); openItem.setMnemonic(KeyEvent.VK_O); openItem.addActionListener(new OpenListener()); // Create a Print menu item. JMenuItem printItem = new JMenuItem("Print"); printItem.setMnemonic(KeyEvent.VK_P); printItem.addActionListener(new PrintListener()); // Create an Exit menu item. JMenuItem exitItem = new JMenuItem("Exit"); exitItem.setMnemonic(KeyEvent.VK_X); exitItem.addActionListener(new ExitListener()); // Create a JMenu object for the File menu. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); // Add the menu items to the File menu. fileMenu.add(openItem); fileMenu.add(printItem); fileMenu.add(exitItem); // Create the menu bar. JMenuBar menuBar = new JMenuBar(); // Add the file menu to the menu bar. menuBar.add(fileMenu); // Set the windows menu bar. setJMenuBar(menuBar);

Short Answer 1. 3. Single selection mode An uneditable combo box combines a button with a list, and allows the user to only select items from its list. An editable combo box combines a text field and a list. In addition to selecting items from the list, the user may also type input into the text field. The default type of combo box is uneditable.

Chapter 14

L-27

5.

A mnemonic is a key on the keyboard that you press in combination with the a key to quickly access a component such as a button. When you assign a mnemonic to a button, the user can click the button by holding down the a key and pressing the mnemonic key. A tool tip is text that is displayed in a small box when the user holds the mouse cursor over a component. The box usually gives a short description of what the component does. The item is deselected, which causes the check mark to disappear. The checked menu item component also generates an action event. Because, as the user moves the JSlider components knob, it will only take on values within its established range.

7.

9. 11.

Chapter 14
Multiple Choice and True/False 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. 23. 25. 27. 29. 31. 33. 35. c b b d c a d c c c b True True False True True False False

L-28

Appendix L

Answers to Odd-Numbered Review Questions

Find the Error 1. 3. 5. The tag should specify the file MyApplet.class instead of MyApplet.java. Call repaint instead of paint. The class must provide all of the methods specified by the MouseListener interface.

Algorithm Workbench 1. 3.
<center><h1>My Home Page</h1></center>

Line Line Line Line Line Line Line Line Line

1: Change JFrame to JApplet 3: Change to public void init() 5: Delete 6: Delete 8: Delete 9: Delete 15: Delete 16: Delete 17: Delete

5.

private class MyMouseMotionListener extends MouseAdapter { public void mouseMoved(MouseEvent e) { mouseMovements += 1; } }

Short Answer 1. 3. It is executed by the users system. Applets are important because they can be used to extend the capabilities of a Web page. Web pages are normally written in Hypertext Markup Language (HTML). HTML is limited, however, because it merely describes the content and layout of a Web page, and creates links to other files and Web pages. HTML does not have sophisticated abilities such as performing math calculations and interacting with the user. A programmer can write a Java applet to perform these types of operations and associate it with a Web page. Some browsers, such as Microsoft Internet Explorer and older versions of Netscape Navigator, do not directly support the Swing classes in applets. These browsers require a plug-in in order to run applets that use Swing components. If you are writing an applet for other people to run on their computers, there is no guarantee that they will have the required plug-in. If this is the case, you should use the AWT classes instead of the Swing classes for the components in your applet. When the component is first displayed and is called again any time the component needs to be redisplayed.

5.

7.

Chapter 15

L-29

9.

If you want to load the sound file and keep it in memory so it can be played more than once, or if you want to play the sound file repeatedly.

Chapter 15
Multiple Choice and True/False 1. 3. 5. 7. 9. b d d True False

Find the Error 1. The recursive method, myMethod, has no base case. So, it has no way of stopping.

Algorithm Workbench 1.
public static void main(String [] args) { String str = "test string"; display(str, 0); } public static void display(String str, int pos) { if (pos < str.length()) { System.out.print(str.charAt(pos)); display(str, pos + 1); } }

3. 5. 7.

10 55 public static int factorial(int num) { int fac = 1; for (int i = 1; i <=num; i++) { fac = fac * i; } return fac; }

L-30

Appendix L

Answers to Odd-Numbered Review Questions

Short Answer 1. 3. An iterative algorithm uses a loop to solve the problem, while a recursive algorithm uses a method that calls itself. For Question 3 the base case is reached when arg is equal to 10. For Question 4 the base case is also reached when arg is equal to 10. For Question 5 the base case is reached when num is less than or equal to 0. Recursive algorithms are usually less efficient than iterative algorithms. This is because a method call requires several actions to be performed by the JVM, such as allocating memory for parameters and local variables, and storing the address of the program location where control returns after the method terminates. The value of an argument is usually reduced.

5.

7.

Вам также может понравиться