Sei sulla pagina 1di 9

Multiple Choice

1. When a program is finished using a file, it should do this: (Pg. 230) a. Erase the file c. Throw an exception 2. This keyword creates an object: (Pg. 167) a. create c. new 3. This type of method does not return a value: (Pg. 274) a. null c. Empty 4. When an exception is generated, it is said to have been: (Pg. 766) a. built c. caught b. thrown d. killed b. void d. Anonymous b. object d. construct b. Close the file d. Reset the read position

5. Two or more methods in a class may have the same name, as long as this is different: (Pg. 338) a. their return values c. their parameter lists b. their access specifier d. their memory address

6. This array field holds the number of elements that the array has: (Pg. 512) a. size c. length b. elements d. width

7. Each element of an array is accessed by a number known as a(n): (Pg. 512) a. subscript c. address b. size delarator d. specifier

8. When an array is passed as an argument to a method, this is actually passed: (Pg. 456) a. a copy of the array c. a reference to the array b. the name of the array d. None of these. You cannot pass an array.

9. This is a section of code that gracefully responds to exceptions: (Pg. 766) a. exception generator c. exception handler b. exception manipulator d. exception monitor

Short Answer (Pgs. 233, 516, 772)


1. Assuming that array1 and array2 are both array reference variables, why is it not possible to assign the contents of the array referenced by array2 to the array referenced by array1 with the following statement?
(Figure 8-9) array1 = array2;

By using the assignment operator on the variables, you are simply copying the reference from one array to another. In effect, both array1 and array2 will point to the same location in memory, and anything thats changed in one will be changed in the other. Arrays must be copied element-by-element using a loop to get a true duplication of an array.

2. What is meant when it is said that an exception is thrown? Where does execution resume after an exception has been thrown and caught?

Throwing an exception means that an error or unexpected event occurred during the running of a program. Exceptions are either caught and handled by the program, or sent to the default exception handler. After an exception is thrown and caught, execution resumes immediately after the catch statement, and not at the location where the exception was thrown.

3. What does it mean to let the user control a loop?

A user-controlled loop is one where the user determines whether or not you must execute another iteration of the loop. These are most commonly found in input-validation loops, where the user must enter a predetermined value, and cannot continue until the user enters valid information. These loops are contrasted with count-controlled loops, whereby a loop will only execute a set number of times before terminating.

Arrays (Pg. 235, modified) A hotels occupancy rate is calculated as follows: Occupancy rate = number of rooms occupied / total number of rooms Write a program that calculates the occupancy rate for a hotel. The program should start by asking for the number of floors in the hotel and the number of rooms per floor (assume each floor has the same number of rooms). Then, for each floor, ask for the number of rooms occupied (assume valid input). Give the average number of occupied rooms per floor. Then, give the occupancy rate for the hotel. Additionally, give the average number of occupied rooms per floor and the floors above occupancy. Sample run: Enter the number of floors: 5 Enter the number of rooms per floor: 10 Floor 1: 5 Floor 2: 8 Floor 3: 6 Floor 4: 2 Floor 5: 4 Average floor occupancy: 5 The occupancy rate is: 0.5 The following floors are above average occupancy: 2 3

import java.util.Scanner; public static void main(String [] args) { Scanner in new Scanner(System.in); System.out.print("Enter the number of floors: "); int floors = in.nextInt(); System.out.print("Enter the number of rooms per floor: "); int rooms = in.nextInt(); // create and initialize the occupancy array int [] roomOcc = new int[floors]; for(int i=0; i<floors; i++) { System.out.print("Floor " + (i+1) + ": "); roomOcc[i] = in.nextInt(); }//end: for(i) // Get the total number of occupants int sum = 0 for(int i=0; i<floors; i++) { sum = sum + roomOcc[i]; }//end: for(i) // Calculate average and the occupancy rate int avg = sum / floors; double totalRooms = floors * rooms; double rate = sum / totalRooms; // Print information System.out.println("Average floor occupancy: " + avg); System.out.println("The occupancy rate is: " + rate); // Print above-average information System.out.println("The following floors are above occupancy:"); for(int i=0; i<roomOcc.length; i++){ if(roomOcc[i] > avg) { int floor = i+1; System.out.println(floor); } }//end: for(i)

File Input & Output (Pg. 236) Write a method that, given the name of an input file, displays the contents of the file to the screen. Each line in the file should be preceded with a line number followed by a colon. The line numbering should start at 1. Remember to deal w/ IOExceptions by using a try/catch block!
public static void printFile(String filename) { try { // Open file File f = new File(filename); Scanner fin = new Scanner(f); // Line counter int lineNum = 1; // Read from file while(fin.hasNext() { String line = fin.nextLine(); System.out.println(lineNum + ": " + line); } // Close file fin.close(); } catch( IOException e ) { System.out.println("Problem in printFile"); }

Large Program Write a program that takes the name of a file as its input. It will then read in 30 days of temperature data and output which days were more than twice as hot as the average temperature. The following methods have been created and are available for you to use: String promptFileName(Scanner in) int [] getInputData(Scanner fin) int [] getReallyHotDays(int [] temps, int avgTemp) Make sure to deal with all I/O exceptions. Sample Run: Enter File Name: may.txt The following days were really hot: 2, 19

import java.io.*; import java.util.Scanner; public class LargeProgram { public static void main(String [] args) { // Get user Scanner and prompt for file name Scanner keyboard = new Scanner(System.in); String filename = promptFileName(keyboard) try { // Open file File f = new File(filename); Scanner fileIn = new Scanner(f); // Get input data using method int [] temperatures = getInputDate(fileIn); // Close file fileIn.close(); // Calculate sum int sum = 0; for(int i=0; i<temperatures.length; i++) { sum = sum + temperatures[i]; } // Calculate average int avg = sum / temperatures.length; // Get the hot days of the month using method int [] hotDays = getReallyHotDays(temperatures, avg); // Print the info to the screen System.out.print("The following days were really hot:"); System.out.print(hotDays[0]); for(int i=1; i<hotDays.length; i++) { System.out.print(", " + hotDays[i]); } } catch( IOException e ) { System.out.println("Problem with File"); }

}//end: main() }//end: LargeProgram

Method Headers For the following method descriptions, write the appropriate method header. DO NOT write the body of the method. Given a filename and a character, return the number of times the character occurs in the file.

private static int countCharacters(String filename, char ch)

Print the maximum number in an array of integers

private static void printMaximum(int [] intArray)

Convert pounds to kilograms

private static double convertToKilo(double pounds)

Return a boolean value based on whether or not the given integer is prime

private static boolean isPrime(int num)

Tracing double [] d = {3, 2, -2, 5, 10}; for(int i=0; i<d.length (a); i++) { if(d[i] % 2 == 0) { //(b) d[i] = d[i] + 1; } else { System.out.println(d[i]); } } i) How many times is condition (a) checked? 6 ii) How many times id condition (b) checked? 5 iii) What is the output of the code sequence? 3 5 iv) What are the final values in d? {3, 3, -1, 5, 11} boolean [] b = {true, true, false, true}; int [] arr = {0, 3, -2, -1, 2, -1, 2}; int j = 0; while( b[arr [0]] ) { //(a) arr[0] = arr[0] + arr[j]; j++; } System.out.println(j); i) What is the output of the code sequence? 5 ii) What is the final value in arr[0]? 2 iii) How many times is condition (a) checked? 6

Potrebbero piacerti anche