Top Posters
Since Sunday
g
3
3
2
J
2
p
2
m
2
h
2
s
2
r
2
d
2
l
2
a
2
A free membership is required to access uploaded content. Login or Register.

Java Software Solutions Ch2 Data and Expressions.docx

Uploaded: 6 years ago
Contributor: oseven
Category: Programming
Type: Other
Rating: N/A
Helpful
Unhelpful
Filename:   Java Software Solutions Ch2 Data and Expressions.docx (46.76 kB)
Page Count: 29
Credit Cost: 1
Views: 160
Last Download: N/A
Transcript
Java Software Solutions Chapter 2 Data and Expressions 2.1 Multiple-Choice Questions Use the following class definition to answer the questions below. public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } 1) The program will print the word "Here" and then print A) "There Everywhere" on the line after "Here" B) "There" on the line after "Here" and "Everywhere" on the line after "There" C) "There Everywhere" on the same line as "Here" D) "ThereEverywhere" on the same line as "Here" E) "ThereEverywhere" on the line after "Here" Answer: C Explanation: C) System.out.print will output the word "Here" but will leave the cursor at that point rather than starting a new line. The next statement will output "There Everywhere" immediately after the word "Here". Since there is a blank space within the quote marks for "There", there is a blank space inserted between "There" and "Everywhere". 2) The final println command will output A) "But not in Texas" B) "But notin Texas" C) "But not" on one line and "in Texas" on the next line D) "But not+in Texas" E) "But not + in Texas" Answer: B Explanation: B) The "+" performs String concatenation, so that "But not" and "in Texas" are concatenated together. Notice that there is no blank space after "not" or before "in" so that when they are concatenated, they are placed together without a blank space. 3) How many lines of output are provided by this program? A) 1 B) 2 C) 3 D) 4 E) 5 Answer: B Explanation: B) There will be one line of output for the first two statements combined because the print statement does not return the cursor to start a new line. And since the second statement is a println, it returns the cursor and the last println outputs its message on a separate line. 4) A reasonable documentation comment for this program might be A) // a program that demonstrates the differences between print, println and how + works B) // a program that outputs a message about Texas C) // a program that demonstrates nothing at all D) // a program that outputs the message "Here There Everywhere But not in Texas" E) // a program that contains three output statements Answer: A Explanation: A) Remember that comments should not state the obvious (ruling out D and E) but instead should explain what the program is doing or why. This program demonstrates print and println and +. 5) Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ________ lines of text A) 1 B) 2 C) 3 D) 4 E) 5 Answer: B Explanation: B) The \t escape sequence inserts a tab, but leaves the cursor on the same line. The \n escape sequence causes a new line to be produced so that "4 dinner" is output on the next line. The escape sequence \r causes the carriage to return (that is, the cursor to be moved back to the left margin) but because it does not start a new line, "2night" is output over "4 dinn" resulting in a second line that looks like "2nighter". 6) If you want to output the text "hi there", including the quote marks, which of the following could do that? A) System.out.println("hi there"); B) System.out.println(""hi there""); C) System.out.println("\"hi there"); D) System.out.println("\"hi there\""); E) none, it is not possible to output a quote mark because it is used to mark the beginning and ending of the String to be output Answer: D Explanation: D) \" is an escape sequence used to place a quote mark in a String, so it is used here to output the quote marks with the rest of the String. 7) The word println is a(n) A) method B) reserved word C) variable D) class E) String Answer: A Explanation: A) The word println is passed as a message to the System.out object, and so println is a method. 8) A Java variable is the name of a A) numeric data value stored in memory B) data value stored in memory that can not change during the program's execution C) data value stored in memory that can change its value but cannot change its type during the program's execution D) data value stored in memory that can change both its value and its type during the program's execution E) data value or a class stored in memory that can change both its value and its type during the program's execution Answer: C Explanation: C) A variable can change its value as long as it is within the same type, but the variable cannot change type. A constant is similar to a variable but it cannot change its value. Variables can be numeric but are not restricted to being numeric, they can also be boolean, char, or an object of any class. 9) Of the following types, which one cannot store a numeric value? A) int B) byte C) float D) char E) all of these can store numeric values Answer: D Explanation: D) int and byte are used to store whole numbers (integers) and float is used to store a real or floating point value (value with a decimal point). A char stores a single character including letters, punctuation marks and digits. However, storing the numeric digit '5' is not the same as storing the number 5. 10) What value will z have if we execute the following assignment statement? float z = 5 / 10; A) z will equal 0.0 B) z will equal 0.5 C) z will equal 5.0 D) z will equal 0.05 E) none of the above, a run-time error arises because z is a float and 5 / 10 is an int Answer: A Explanation: A) 5 and 10 are both int values, so 5 / 10 is an integer division. The result is 0. Even though z is a float and can store the real answer, 0.5, it only gets 0 because of the integer division. In order to get 0.5, we would have to first cast 5 or 10 as a float. 11) A cast is required in which of the following situations? A) using charAt to take an element of a String and store it in a char B) storing an int in a float C) storing a float in a double D) storing a float in an int E) all of the above require casts Answer: D Explanation: D) For A, charAt returns a char, so there is no problem. In B and C, the situations are widening operations taking a narrower type and storing the value in a wider type. Only in D is there a situation where a wider type is being stored in a narrower type, so a cast is required. 12) If x is an int and y is a float, all of the following are legal except which assignment statement? A) y = x; B) x = y; C) y = (float) x; D) x = (int) y; E) all of the above are legal Answer: B Explanation: B) Since x is an int, it cannot except a float unless the float is cast as an int. There is no explicit cast in the assignment statement in B. In A, a cast is not necessary because a float (y) can accept an int value (x), and in C and D, explicit casts are present making them legal. 13) Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f; A) *, /, +, - B) *, +, /, - C) +, *, /, - D) +, /, *, - E) +, -, *, / Answer: C Explanation: C) Order of precedence is any operator in ( ) first, followed by * and / in a left-to-right manner, followed by + and - in a left-to-right manner. So, + is first since it is in ( ), followed by * followed by / since * is to the left of /, followed finally by -. Both * and / are at the same level of precedence but evaluated left-to-right. The same is true of + and -. 14) What will be the result of the following assignment statement? Assume b = 5 and c = 10. int a = b * (-c + 2) / 2; A) 30 B) -30 C) 20 D) -20 E) -6 Answer: D Explanation: D) The unary minus is applied first giving -c + 2 = -8. Next, the * is performed giving 5 * -8 = -40, and finally the / is performed giving -40 / 2 = -20. 15) Which of the following is true regarding the mod operator, %? A) It can only be performed on int values and its result is a double B) It can only be performed on int values and its result is an int C) It can only be performed on float or double values and its result is an int D) It can only be performed on float or double values and its result is a double E) It can be performed on any numeric values, and the result always is numeric Answer: E Explanation: E) Mod, or modulo, returns the remainder that results from a division. The remainder is always is numeric. Although usually integer values are used, the % operator may be used on all kinds of numeric data. 16) Assume that x, y, and z are all integers (int) equal to 50, 20, and 6 respectively. What is the result of x / y / z? A) 0 B) 12 C) 16 D) A syntax error as this is syntactically invalid E) A run-time error because this is a division by 0 Answer: A Explanation: A) This division is performed left to right, so first 50 / 20 is performed. Since 50 and 20 are ints, this results in 2. Next, 2 / 6 is performed which is 0. Notice that if the division were performed right to left, the evaluation would instead be 50 / (20 / 6) = 50 / 3 = 16. 17) What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5? A) 15 B) 105 C) 10 5 D) x+y E) An error since neither x nor y is a String Answer: A Explanation: A) Java first computes x+y and then casts it as a String to be output. x + y = 10 + 5 = 15, so the statement outputs 15. 18) What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5? A) 15 B) 105 C) 10 5 D) x+y E) An error since neither x nor y is a String Answer: B Explanation: A) The "" causes the rest of the expression to be treated as a String, and so the two + signs are used as String concatenation. Therefore x + y becomes x concatenated with y, or 105. 19) If you want to store into the String name the value "George Bush", you would do which statement? A) String name = "George Bush"; B) String name = new String("George Bush"); C) String name = "George" + " " + "Bush"; D) String name = new String("George" + " " + "Bush"); E) Any of the above would work Answer: E Explanation: E) There are two ways to store a character string into a String variable, by constructing a new String using "new String(string value);" or by using an assignment statement, so either A or B will work. In C and D, we have variations where the String concatenation operator + is used. So all four approaches will work. 20) Consider having three String variables a, b, and c. The statement c = a + b; also can be achieved by saying A) c = a.length( ) + b.length( ); B) c = (int) a + (int) b; C) c = a.concat(b); D) c = b.concat(a); E) c = a.plus(b); Answer: C Explanation: C) The statement c = a + b uses the concatenation operator + (not to be confused with numeric addition). The same result can be achieved by passing a the concat message with b as the parameter. Answer D will set c to be b + a rather than a + b. 21) If the String major = "Computer Science", what is returned by major.charAt(1)? A) 'C' B) 'o' C) 'm' D) "C" E) "Computer" Answer: B Explanation: B) Neither D nor E would be correct because charAt returns a char (single character) whereas these answers are Strings. So, the question is, which character is returned? In Java, the first character of a String is numbered 0. So charAt(1) returns the second character of the String, or 'o'. 22) Which of the following would return the last character of the String x? A) x.charAt(0); B) x.charAt(last); C) x.charAt(length(x)); D) x.charAt(x.length( )-1); E) x.charAt(x.length( )); Answer: D Explanation: D) Since last is not defined, B is syntactically invalid. The 0th character is the first in the String, so A is true only if the String has a single character. The answer in C is syntactically invalid as length can only be called by passing the message to x. Finally, D and E are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so E would result in a run-time error. 23) Suppose that String name = "Frank Zappa". What will the instruction name.toUpperCase( ).replace('A', 'I'); return? A) "FRANK ZAPPA " B) "FRINK ZIPPI" C) "Frink Zippi" D) "Frank Zappa" E) "FrInk ZIppI" Answer: B Explanation: B) The toUpperCase method returns the String as all upper case characters, or "FRANK ZAPPA". The replace method will replace each instance of 'A' with 'I'. 24) Which library package would you import to use NumberFormat and DecimalFormat? A) java.beans B) java.io C) java.lang D) java.text E) java.util Answer: D Explanation: D) Both of these classes are used for "text processing", that is, to handle values like Strings. Such classes are found in java.text. You might think these would be in java.io, but this library has classes related to input and sending output to locations other than the monitor. 25) Which library package would you import to use the class Random? A) java.beans B) java.io C) java.lang D) java.text E) java.util Answer: E Explanation: E) This is a java numeric utility, and so is found in the java.util package. 26) The Random class has a method nextFloat( ) which returns a random float value between A) -1 and +1 B) 0 and 1 C) 0 and 99 D) 1 and 100 E) -2,147,483,648 and +2,147,483,647 Answer: B Explanation: B) The method nextFloat( ) returns a float value between 0 and 1 so that it may be used as a probability. 27) If you want to output a double so that at least 1 digit appears to the left side of the decimal point and exactly 1 digit appears to the right side of the decimal point, which pattern would you give a DecimalFormat variable when you instantiate it? A) "0.0" B) "0.#" C) "0.0#" D) "0.##" E) "#.#" Answer: A Explanation: A) The pattern "0.0" says to output all of the digits to the left of the decimal point or a 0 if there are none (you want at least 1 digit to the left, including a 0 if there are no digits) and exactly one digit to the right of the decimal point, even if the digit is 0. The patterns "0.#" and "#.#" would not output any digits to the right side of the decimal point if the value had no decimal portion (e.g., 39.0). The patterns in C and D can output up to 2 values to the right of the decimal point. 28) Consider the double value likelihood = 0.013885. What would be output if DecimalFormat dformatter = DecimalFormat("0.00##"); and you execute System.out.println(df.format(likelihood)); ? A) 0.013885 B) 0.0139 C) 0.014 D) .0139 E) .014 Answer: B Explanation: B) The format "0.00##" means that at least 1 digit should appear to the left of the decimal point, even if it is 0, that at least two digits should appear to the right of the decimal point even if they are zeros, and if there are two additional digits to the right, they should also be printed, rounding the value off as needed. So, this gives 0.0139 since the number, 0.013885 will be rounded up to 0.0139. 29) Using getCurrencyInstance( ) formats a variable, automatically inserting A) decimal point for cents B) dollar sign C) percent sign D) all three E) A and B but not C Answer: E Explanation: D) getCurrencyInstance will format a double or float variable so that it has 2 digits to the right of the decimal point and a dollar sign preceding the value. getPercentInstance is used to format a double or float to be output with a percent sign. 30) What value will z have if we execute the following assignment statement? int z = 50 / 10.00; A) 5 B) 5.0 C) 50 D) 10 E) none of the above, a run-time error arises because z is an int and 50 / 10.00 is not Answer: E Explanation: E) Because 10.00 is not an int, the division produces a double precision value which cannot be stored in the int z. For this to work, the result of the division must be cast as an int before being stored in z, or the value 10.00 would have to first be cast as an int before the division takes place. 31) Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x? A) Math.sqrt(x*x); B) Math.sqrt((int) x); C) Math.sqrt(Math.abs(x)); D) Math.abs(Math.sqrt(x)); E) Math.sqrt(-x); Answer: C Explanation: C) Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x) causes a run-time error, but Math.sqrt(Math.abs(x)) does not since x is first converted to its positive equivalent before the square root is performed. Answer A returns x (square root of x2 is x). In answer B, casting x to an int will not resolve the problem if x is negative. In answer D, the two Math functions are performed in opposite order and so if x is negative, it still generates a run-time error. Answer E only will work if x is not positive and so if x is positive, it now generates a run-time error. 32) Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then would output x as 36%? A) System.out.println(x); B) System.out.println(nf); C) System.out.println(nf.x); D) System.out.println(nf.format(x)); E) System.out.println(format(x)); Answer: D Explanation: D) nf is an object and so must be passed a message to use it. The method to format a float or double is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do this is nf.format(x). The answer in A merely outputs 0.362491 while the answers to B, C, and E are syntactically invalid. For the following questions, refer to the class defined below: import java.util.Scanner; public class Questions33_34 { public static void main(String[ ] args) { int x, y, z; double average; Scanner scan = new Scanner(System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } 33) Questions33_34 computes A) The correct average of x, y and z as a double B) The correct average of x, y and z as an int C) The average of x, y, and z as a double, but the result may not be accurate D) the sum of x, y and z E) the remainder of the sum of x, y and z divided by 3 Answer: C Explanation: C) Because the division is an int division, even though the result is stored in a double, the resulting double may not be accurate. For instance, if x, y and z are 1, 2, and 4, the double average should be 2.33333 but average will instead be 2.00000. 34) What is output if x = 0, y = 1 and z = 1? A) 0 B) 0.0 C) 0.6666666666666666 D) 0.6666666666666667 E) 0.67 Answer: B Explanation: B) The division is performed as an int division since x, y, z, and 3 are all ints. Therefore, average gets the value 0.0. It is output as 0.0 instead of 0 because average is a double, which outputs at least one decimal digit unless specified otherwise using the DecimalFormat class. 35) If you want to draw a red circle inside of a green square in an applet where the paint method is passed a Graphics object called page, which of the following sets of commands might you use? A) page.setColor(Color.green); page.fillRect(50, 50, 100, 100); page.setColor(Color.red); page.fillOval(60, 60, 80, 80); B) page.setColor(Color.red); page.fillOval(60, 60, 80, 80); page.setColor(Color.green); page.fillRect(50, 50, 100, 100); C) page.setColor(Color.green); page.fillRect(60, 60, 80, 80); page.setColor(Color.red); page.fillOval(50, 50, 100, 100); D) page.setColor(Color.red); page.fillOval(50, 50, 100, 100); page.setColor(Color.green); page.fillRect(60, 60, 80, 80); E) any of the above would accomplish this Answer: A Explanation: A) You need to draw the background (larger) image first. This is the square in green. The square will be larger, so it starts at 50, 50 and is of size 100 x 100. Next, draw the circle in red inside the square, so it will start at 60, 60 and be smaller in size at 80 x 80. Answer B will accomplish the same drawings but in opposite order so that the circle is drawn over, thus blocking it as if it weren't there. Consider the following paint method and answer the questions below: public void paint(Graphics page) { page.setColor(Color.blue); page.fillRect(50, 50, 100, 100); page.setColor(Color.white); page.drawLine(50, 50, 150, 150); page.drawLine(50, 150, 150, 50); page.setColor(Color.black); page.drawString("A nice box", 50, 170); } 36) The figure drawn in this applet is A) a blue square B) a blue square with two white lines drawn horizontally through it C) a blue square with two white lines drawn diagonally through it D) a blue square with two white lines drawn vertically through it E) a white square with two blue lines drawn vertically through it Answer: C Explanation: C) The color set before fillRect is blue, so the square is blue. The two lines are white and they are drawn from the upper left corner (50, 50) to the lower right corner (150, 150) and from the lower left corner (50, 150) to the upper right corner (150, 50). 37) The String "A nice box" is drawn A) above the box B) to the left of the box C) to the right of the box D) below the box E) inside the box Answer: D Explanation: D) The String is drawn at coordinates (50, 170) so the x-coordinate lines up with the left-side of the box, but the y-coordinate, 170, is below the bottom edge of the box which is at y=150. 38) You specify the shape of an oval in a Java applet by defining the oval's A) arc locations B) center and radius C) bounding box D) foci E) none of the above, it is not possible to draw an oval in a Java applet Answer: C Explanation: C) The bounding box is the box that defines the height and width of the oval along with the (x, y) coordinate that are the highest and left-most point of the oval. 39) In order to create a constant, you would use which of the following Java reserved words? A) private B) static C) int D) final E) class Answer: D Explanation: D) The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable. 40) If a, b, and c are int variables with a = 5, b = 7, c = 12, then the statement int z = (a * b - c) / a; will result in z equal to A) 0 B) 4 C) 5 D) -5 E) 23 Answer: B Explanation: B) (a * b - c) / a = (5 * 7 - 12) / 5 = (35 - 12) / 5 = 23 / 5, and since 23 and 5 are int values, the division is performed as an int division, or 23 / 5 = 4. 41) Java is a strongly typed language. What is meant by "strongly typed"? A) Every variable must have an associated type before you can use it B) Variables can be used without declaring their type C) Every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of that type D) Variables are allowed to change type during their existence in the program as long as the value it currently stores is of the type it is currently declared to be E) Variables are allowed to change types during their existence in the program but only if the change is to a narrower type Answer: C Explanation: C) Strong typing is a property of a programming language whereby the variable's type does not change during the variable's existence, and any value stored in that variable is of that type. The reason that strong typing is important is it guarantees that a program that was successfully compiled will not have run-time errors associated with the misuse of types for the variables declared. 42) As presented in the Software Failure, the root cause of the Mars Climate Orbiter problem was A) the cost of the project B) an inability to track the orbiter at long distances C) atmospheric friction D) a communication issue between subsystems E) none of the above Answer: D Explanation: D) The cause was determined to be an embarrassing communication issue between subsystems. The navigation subsystem used imperial units of measure (pound-force) and the spacecraft's software itself expected data in metric units (newtons). 2.2 True/False Questions 1) If x is a string, then x = new String("OH"); and x = "OH"; will accomplish the same thing. Answer: TRUE Explanation: In Java, to instantiate (assign a value to) an object, you must use new and the class's constructor. However, since Strings are so common in Java, they can be instantiated in a way similar to assigning primitive types their values. So, both of the above assignment statements will accomplish the same task. 2) If x is the String "Hi There", then x.toUpperCase( ).toLowerCase( ); will return the original version of x. Answer: FALSE Explanation: x.toUpperCase( ) returns x as all capital letters, while x.toLowerCase( ) will return x as all lower case letters. So, this code will first convert x to all upper case letters and then convert the new version to all lower case characters. 3) If String name = "George W. Bush"; then the instruction name.length( ); will return 14. Answer: TRUE Explanation: There are 14 characters between the quote marks including two blanks and a period, 4) If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true. Answer: TRUE Explanation: Since "ABCD" is not the same as "abcd", the equals method returns false, but by ignoring case in equalsIgnoreCase, the two are considered to be the same. 5) Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length( ), in order to use either the Scanner or Math classes, you pass messages directly to the class name, as in Math.abs( ) or scan.nextInt( ). Answer: TRUE Explanation: The Math and Scanner classes use methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. 6) In order to generate a random number, you must use Math.random( ). Answer: FALSE Explanation: There is also a Random class available in java.util. This class can generate random int, float, and double values. This is a better mechanism for generating random numbers because you can instantiate several different random number generators. 7) A double is wider than a float and a float is wider than an int. Answer: TRUE Explanation: Wider types are larger in size or can store a greater range of values. The double is 64 bits whereas the float is 32 bits and the float, because of the way it is stored, can store a significantly larger range of values than the int. 8) A variable of type boolean will store either a 0 or a 1. Answer: FALSE Explanation: A boolean variable can store only one of two values, but these values are the reserved words true and false. In C, C++, and C# booleans are implemented as int variables that store only a 0 or a 1, but in Java, the authors of the language opted to use the boolean literals true and false as this is considered to be semantically more understandable (and is much safer). 9) In Java, 'a' and 'A' are considered to be different values. Answer: TRUE Explanation: Characters (char) values are stored using ASCII, and 'a' and 'A' have different ASCII values as well as different Unicode values. 10) You cannot cast a String to be a char and you cannot cast a String which stores a number to be an int, float or double. Answer: TRUE Explanation: There is no mechanism available to cast a String to one of the primitive types, but there are methods available to perform a similar action and return a character at a given location (charAt) or to return the int, float or double value equivalent to the number stored in the String. 11) The values of (double) 5 / 2 and (double) (5 / 2) are identical. Answer: FALSE Explanation: In the first expression, the (double) cast applies to the int 5, changing it to the double value, 5.0. Then 5.0 / 2 is calculated, yielding the double value, 2.5. In the second expression the int division is performed first, yielding the value 2. 2 is then changed to a double, yielding the double value, 2.0. 12) The Java graphics coordinate system is similar to the coordinate system one finds in mathematics in every respect. Answer: FALSE Explanation: The Java coordinate system is similar to the one from mathematics, but the following important differences are present: (1) The Java coordinate system only uses non-negative integers as coordinates, not real values, and no negative coordinates are allowed; (2) The (0, 0) location is a the top-left of the coordinate system, with positive y running downwards instead of at the bottom-left, with positive y running upwards. 13) Many Java drawing shapes are specified using a bounding rectangle. Answer: TRUE Explanation: Although a few shapes (like a line) are specified using start-point-end-point combinations, most Java shapes use a bounding rectangle specified by a starting point, width, and height. 14) There are three ways that data conversion may occur?by assignment, by promotion, by casting. Answer: TRUE Explanation: Assignment conversion occurs when a value on the right side of the assignment operator is converted prior to being stored in the variable on the left. Promotion occurs within an expression when values of differing widths are combined. Casting is a programmer's explicit way to control the data conversion process. 15) Java is able to represent 255 * 255 * 255 = 16,581,375 distinct colors. Answer: FALSE Explanation: The red, green, and blue color components range between 0 and 255, yielding 256 distinct values for each. Therefore, 256 * 256 * 256 = 16,777,216 distinct colors can be represented. 16) As explained in the Software Failure, the Mars Lander most likely crash landed when its descent engines cut off too high over the Mars surface. Answer: TRUE Explanation: The software on board the lander mistook the vibrations caused by the deployment of the lander's legs for the vibration caused by actually landing on the planet's surface. 2.3 Free-Form Questions 1) Write a set of instructions to prompt the user for an int value and input it using the Scanner class into the variable x and prompt the user for a float value and input it using the Scanner class into the variable y. Answer: Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer"); int x = scan.nextInt( ); System.out.println("Enter a float"); float y = scan.nextFloat( ); 2) Provide an example of how you might use a boolean, a float, a char, a String, and an int. Answer: boolean: to store whether a person is of voting age or not float: to store someone's GPA char: to store someone's middle initial String: to store someone's social security number int: to store someone's age 3) Explain, in words, what the following statement computes: int z = (int) Math.ceil(Math.sqrt(x) / Math.sqrt(y)); Answer: The integer value which bounds sqrt(x) / sqrt(y) where bounds means it is equal to the result of the division or the next int larger than the result of the division if the result has a remainder. 4) Given four int values, x1, x2, y1, y2, write the code to compute the distance between the two points (x1, y1) and (x2, y2), storing the result in the double distance. Answer: double distance = Math.sqrt(Math.pow(x1 - y1, 2) + Math.pow(x2 - y2, 2)) ; 5) Write an assignment statement to compute the gas mileage of a car where the int values miles_traveled and gallons_needed have already been input. The variable gas_mileage needs to be declared and should be a double. Answer: double gas_mileage = (double) miles_traveled / gallons_needed; The reason that the value miles_traveled is cast as a double is to ensure that the division is performed as a double and not an int. 6) Write the paint method for an applet so that it contains 4 concentric circles (each circle is inside the previous circle), where the largest circle is bounded by a 400x400 box and the smallest is bounded by a 100x100 box. Each circle is centered on an applet that is 400x400. Make each circle a different color of your choice. Answer: public void paint(Graphics page) { page.setColor(Color.white); page.fillOval(0, 0, 400, 400); page.setColor(Color.yellow); page.fillOval(50, 50, 300, 300); page.setColor(Color.orange); page.fillOval(100, 100, 200, 200); page.setColor(Color.red); page.fillOval(150, 150, 100, 100); } 7) Given two points in an applet represented by the four int variables x1, y1, x2 and y2, write a paint method to draw a line between the two points and write the location of the two points next to the two points. Answer: public void paint(Graphics page) { page.setColor(Color.blue); page.drawLine(x1, y1, x2, y2); page.drawString("" + x1 + ", " + y1, x1, y1); page.drawString("" + x2 + ", " + y2, x2, y2); } 8) An applet is 200x200. Write the Strings "North", "South", "East", and "West" at the four edges of the applet where they should appear as if on a map. Use the color black for the text. Answer: public void paint(Graphics page) { page.setColor(Color.black); page.drawString("North", 90, 10); page.drawString("South", 90, 190); page.drawString("East", 5, 90); page.drawString("West", 170, 90); } 9) An employer has decided to award a weekly pay raise to all employees by taking the square root of the difference between his weight and the employee's weight. For instance, an employee who weighs 16 pounds less than the employer will get a $4 per week raise. The raise should be in whole dollars (an int). Assume that employerWeight and employeeWeight are both int variables that have been input, write an assignment statement to compute the int value for raise. Answer: raise = (int) Math.sqrt(Math.abs(employerWeight - employeeWeight)); The absolute value of the difference must be taken in case the employee weighs more than the employer, which would then result in an attempt to take the square root of a negative number if Math.abs were not used. After computing the absolute value of the difference, the square root is taken and the result (a double) is cast as an int to be stored in raise. 10) Using the various String methods, manipulate a String called current to be current's last character followed by the remainder of its characters in order, placing the result in a String called rearranged. Answer: String rearranged = current.charAt(current.length( ) - 1) + current.substring(0, current.length( ) - 1); The last character, which is found at charAt(current.length( ) - 1) is the first item in rearranged, followed by the substring of current starting at 0 (the first character) and going to current.length( ) - 2 (the second to last character). 11) How many ways are there to test to see if two String variables, a and b, are equal to each other if we ignore their case (for instance, "aBCd" would be considered equal to "ABcd"). Answer: There are at least 10 ways that this can be done: a.toLowerCase( ).equals(b.toLowerCase( )); b.toLowerCase( ).equals(a.toLowerCase( )); a.toUpperCase( ).equals(b.toUpperCase( )); b.toUpperCase( ).equals(a.toUpperCase( )); a.equalsIgnoreCase(b); b.equalsIgnoreCase(a); a.equalsIgnoreCase(b.toLowerCase( )); a.equalsIgnoreCase(b.toUpperCase( )); b.equalsIgnoreCase(a.toLowerCase( )); b.equalsIgnoreCase(a.toUpperCase( )); 12) How do the statements "import java.util.*;" and "import java.util.Random;" differ from each other? Answer: In the former, all of the classes defined in the java.util library are imported whereas in the latter, only the Random class is imported from the java.util library. The former approach is easier but more time consuming and wasteful of memory, so the latter approach is more appropriate if you only want to use a single class from a given library. 13) Assume that a = "1", b = "2", y = 3 and z = 4. How do the following two statements differ? System.out.println(a + b + y + z); System.out.println(y + z + a + b); Answer: In the first statement, since a and b are Strings, a + b + c + d is treated as String concatenation and the statement outputs 1234. In the second statement, y + z is treated as int addition, which is then cast as a String to be concatenated with y + z, giving 712 instead of 3412 as you might expect. 14) Write a program which will input an int value x, and compute and output the values of 2x and x10 as int values. Answer: import java.util.Scanner; public class Compute14 { public static void main(String[ ] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); int x = scan.nextInt( ); int twoToTheX = (int) Math.pow(2, x); int xToThe10th = (int) Math.pow(x, 10); System.out.println("The results are " + twoToTheX + " and " + xToThe10th); } } 15) What is wrong with the following assignment statement? Assume x and y are both String objects. String z = x.equals(y); Answer: The equals method returns a boolean value, not a String. The values true and false are not the same as the values "true" and "false". 16) Write a program that will input some number of cents (less than 100) and output the number of quarters, dimes, nickels and pennies needed to add up to that amount. Answer: import java.util.Scanner; public class Change { public static void main(String[ ] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter the amount of change"); int amount = scan.nextInt( ); System.out.println("The change for " + amount + " cents is: "); int quarters = amount / 25; System.out.println(" " + quarters + " quarters"); amount = amount - quarters * 25; int dimes = amount / 10; System.out.println(" " + dimes + " dimes"); amount = amount - dimes * 10; int nickels = amount / 5; System.out.println(" " + nickels + " nickels"); amount = amount - nickels * 5; int pennies = amount; System.out.println(" " + pennies + " pennies"); } } 17) Write an output statement which will output the following characters exactly as shown: / ' \" / ' \ Answer: System.out.println("/ \ ' \ \ \" / \ ' \ \ "); 18) Provide three examples of code using assignment statements where one assignment statement would result in a syntax error, one would result in a logical error, and one would result in a run-time error. Answer: int x = 5.0 / 2.0; // syntax error caused by right side providing a double and the left side wants an int double x = (intValue1 + intValue2) / 2; // logical error caused by not casting the division as a double int x = 5 / (y - y); // run-time error caused by division by 0 when y - y is evaluated 19) What are the syntax errors from the following program? public class Enigma { public static void main(String[ ] args) { System.out.println("Input a String"); String x = scan.nextString( ); int size = x.length; char last = x.charAt(size); System.out.println("The last character in your string ", x, " is ", last); } } Answer: There are 3 syntax errors. First, the Scanner class has not been import so that the scan.nextString( ) will yield a syntax error. Second, the statement x.length requires parentheses as length is a method of the class String, so this is a message passed to x. Finally, the System.out.println statement is not valid because of the use of "," instead of "+" to concatenate the various parts of the String. Note that in spite of these syntax errors, there is a run-time error. This error would arise because size will store the length of the String, but the last character will be at location size - 1 instead of size. Thus, the statement char last = x.charAt(size); will result in a run-time error because size is beyond the bounds of the String x.

Related Downloads
Explore
Post your homework questions and get free online help from our incredible volunteers
  1069 People Browsing
 125 Signed Up Today
Your Opinion
What's your favorite coffee beverage?
Votes: 274

Previous poll results: How often do you eat-out per week?