Java Software Solutions, 7e (Lewis/Loftus)
Chapter 6 More Conditionals and Loops
6.1 Multiple-Choice Questions
1) You might choose to use a switch statement instead of nested if-else statements if
A) the variable being tested might equal one of several hundred int values
B) the variable being tested might equal one of only a few int values
C) there are two or more int variables being tested, each of which could be one of several hundred values
D) there are two or more int variables being tested, each of which could be one of only a few values
E) none of the above, you would never choose to use a switch statement in place of nested if-else statements under any circumstance
Answer: B
Explanation: B) The switch statement can only be used if there is a single variable being tested and it is an integral type (an int or a char in Java). Further, because you have to enumerate each possible value being tested, the switch statement only makes sense if the number of values being tested is a small number.
2) If a switch statement is written that contains no break statements whatsoever,
A) this is a syntax error and an appropriate error message will be generated
B) each of the case clauses will be executed every time the switch statement is encountered
C) this is equivalent to having the switch statement always take the default clause, if one is present
D) this is not an error, but nothing within the switch statement ever will be executed
E) none of the above
Answer: E
Explanation: E) Although writing such a switch statement is unusual, it is entirely legal. The normal rules for switch statement execution apply the matching case clause being executed after the switch expression is evaluated. Following that, all subsequent clauses are executed, in order, since there are no break statements to terminate the switch/case execution.
1 Copyright © 2012 Pearson Education, Inc.
3) A continue statement
A) may be used within a while or a do-while loop, but not a for loop
B) is identical to a break statement within Java loops
C) may be used within any Java loop statement
D) may be used within a for loop, but not within a while or a do-while loop
E) none of the above
Answer: C
Explanation: C) Although use of continue statements should be avoided, if possible, they may be used within any of Java's three loops: for, while, and do-while.
Given the following switch statement where x is an int, answer the questions below switch (x) {
case 3 : x += 1;
case 4 : x += 2;
case 5 : x += 3;
case 6 : x++;
case 7 : x += 2;
case 8 : x--;
case 9 : x++
4) If x is currently equal to 5, what will the value of x be after the switch statement executes?
A) 8
B) 6
C) 11
D) 5
E) 10
Answer: C
Explanation: C) Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 5 since x is 5 prior to the switch statement. This changes x to 8, then to 9, then to 11, then to 10, and then finally back to 11.
5) If x is currently equal to 3, what will the value of x be after the switch statement executes?
A) 5 B) 6
C) 11
D) 10 E) 12
Answer: E
Explanation: E) Since there are no break statements, the flow falls through any cases following the one that is first true. The first case to be true is 3 since x is 3 prior to the switch statement. This changes x to 4, then to 6, then to 9, then to 10, then to 12, then to 11, and then finally back to 12.
2 Copyright © 2012 Pearson Education, Inc.
}
6) The statement if (x < 0) y = x; else y = 0; can be rewritten using a conditional operator as
A) y = (x < 0) ? x : 0;
B) x = (x < 0) ? y : 0;
C) (x < 0) ? y = x : y = 0;
D) y = (x < 0);
E) y = if (x < 0) x : 0;
Answer: A
Explanation: A) The conditional operator of Java tests a condition, (x < 0) in this case, and if true, returns the value after the ? (x in this case) and if false, returns the value after the : (0 in this case). The original if statement is to assign y to x if (x < 0) and 0 otherwise. This will be accomplished by assigning y to be x or 0 based on (x < 0), as shown in A. In B, x is assigned the value of y or 0 which is backward. In C, the conditional operator is syntactically invalid. In D, y would be set to either true or false depending on (x < 0), and the statement in E is syntactically invalid.
7) Given the following code, where x = 0, what is the resulting value of x after the for-loop terminates?
for (int i=0;i<5;i++) x += i;
A) 0
B) 4
C) 5
D) 10
E) 15
Answer: D
Explanation: D) Each pass through the for-loop results with the current value of the loop index, i, being added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x + 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3 = 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10.
8) The do loop differs from the while loop in that
A) the while loop will always execute the body of the loop at least once
B) the do loop will always execute the body of the loop at least once
C) the do loop will continue to loop while condition in the while statement is false and the while loop will continue to loop while the condition in the while statement is true
D) the while loop will continue to loop while condition in the while statement is false and the do loop will continue to loop while the condition in the while statement is true
E) none of the above, there is absolutely no difference between the two types of loops
Answer: B
Explanation: B) Because the do loop does not test the condition until after the body of the loop executes, the body will always execute at least one time, but the while loop tests the condition first, and so if the condition is false the first time, the body does not execute even one time.
3 Copyright © 2012 Pearson Education, Inc.
9) How many times will the following loop iterate? int x = 10; do { System.out.println(x); x ; } while (x > 0);
A) 0 times
B) 1 time
C) 9 times
D) 10 times
E) 11 times
Answer: E
Explanation: E) The variable x starts at 10. Each pass through the loop, x is decremented and the loop finally exits once x is not longer greater than 0, which in this case means once x becomes 0. So the loop body executes for x = 10, x = 9, x = 8, and so forth down to x = 0. This is 11 times.
10) Given that s is a String, what does the following loop do? for (int j = s.length( ); j > 0; j ) System.out.print(s.charAt(j-1));
A) it prints s out backwards
B) it prints s out forwards
C) it prints s out backwards after skipping the last character
D) it prints s out backwards but does not print the 0th character
E) it yields a run-time error because there is no character at s.charAt(j-1) for j = 0
Answer: A
Explanation: A) The variable j counts down from the length of the String to 1, each time printing out the character at position j-1. The character at length - 1 is the first character printed and this is the last character of the String. It continues until it reaches j = 1, and prints out the character at position j - 1, or the 0th character, so it prints the entire String backwards.
4 Copyright © 2012 Pearson Education, Inc.
11) The following nested loop structure will execute the inner most statement (x++) how many times? for (int j = 0; j < 100; j++) for (int k = 100; k > 0; k ) x++;
A) 100
B) 200
C) 10,000
D) 20,000
E) 1,000,000
Answer: C
Explanation: C) The outer loop iterates 100 times. Each time it iterates, the inner loop, and the x++ statement, execute 100 times. Therefore, the statement x++ executes 100*100 = 10,000 times.
Consider the following paint method to answer the questions below: public void paint(Graphics page) { int x, y = 200; page.setColor(Color.blue); for (x = 100; x < 200; x += 20) page.fillRect(x, y, 10, y-x);
12) This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed?
A) 4
B) 5
C) 6
D) 10
E) 20
Answer: B
Explanation: B) Since x iterates from 100 up to 200 in units of 20, it iterates 5 times (x = 100, x = 120, x = 140, x = 160, x = 180).
13) The size of each rectangle (bar)
A) increases in height while staying the same width
B) increases in width while staying the same height
C) increases in both width and height
D) stays the same size
E) decreases in height while staying the same width
Answer: E
Explanation: E) The width is a constant 10. The height is y-x where x increases by 20 each iteration, so the height decreases by 20.
5 Copyright © 2012 Pearson Education, Inc.
}
14) What will the following code do? Assume s is a String, x is an int initialized to 10, page is a Graphics object, and this is part of a paint method for an applet. boolean isVowel = false; String vowels = "aeiou"; for (int j = 0; j < s.length( ); j++)
{ for (int k = 0; k < 5; k++) if (s.charAt(j) == vowels.charAt(k)) isVowel = true; if (isVowel) page.drawString(""+s.charAt(j), 10, 15*x++); else page.drawString(""+s.charAt(j), 110, 15*x++); isVowel = false;
A) The String s is printed down the applet in two columns, alternating each letter
B) The String s is printed across the applet with vowels printed in one row and all other characters printed in a row above the vowels
C) The String s is printed across the applet with vowels printed in one row and all other characters printed in a row below the vowels
D) The String s is printed down the applet in two columns with vowels appearing in the left column and all other characters in the right column
E) The String s is printed down the applet in two columns with vowels appearing in the right column and all other characters in the left column
Answer: D
Explanation: D) The inner for loop iterates through the 5 characters in the String vowels to see if the current character in the String s is a vowel or non-vowel. If it is a vowel, it is printed at position 10, 15*x otherwise it is printed in position 110, 15*x. The values 10 and 110 refer to the x-coordinate in the Applet, so vowels are printed on the left side and all other characters are on the right side. By using x++, the y-coordinate is incremented so that the next character is printed below the current character.
15) Which of the following statements are true about Java loops?
A) all three loop statements are functionally equivalent
B) while loops and do loops are essentially the same; but while loops always execute at least once
C) if you know the number of times that a loop is to be performed, the best loop statement to use is a while loop
D) loops may be replaced by an appropriate combination of if-else and switch statements
E) none of the above
Answer: A
Explanation: A) In Java, as in most languages, the looping statements are all essentially equivalent (and almost interchangeable). Their principal difference(s) relate to when the controlling condition is evaluated and whether there is syntax for incrementation/update.
6 Copyright © 2012 Pearson Education, Inc.
}
6.2 True/False Questions
1) A switch statement must have a default clause.
Answer: FALSE
Explanation: The default clause is optional.
2) Control in a switch statement jumps to the first matching case.
Answer: TRUE
Explanation: The switch expression is evaluated and control jumps to the first matching case, then continues from there.
3) Each case in a switch statement must terminate with a break statement.
Answer: FALSE
Explanation: They often do, but if the break statement is not present, the flow of control continues into the next case.
4) The following for-loop is an infinite loop. for (int j = 0; j < 1000; ) i++;
Answer: TRUE
Explanation: This loop initializes j to 0 and compares it to 1000, but does not alter j after each loop iteration. In reality, the loop will terminate with a run-time error eventually once i becomes too large of a value to store in memory, but logically, this is an infinite loop.
5) It is possible to convert any type of loop (while, do, or for) into any other.
Answer: TRUE
Explanation: All loop statements have equivalent expressive power.
6) The following loop is syntactically valid. for (int j = 0; j < 1000; j++) j ;
Answer: TRUE
Explanation: The Java compiler does not care that you are incrementing j in the loop but decrementing j in the loop body. Logically, this loop makes no sense because j will continuously be incremented and decremented so that it never reaches 1000, but there is nothing wrong with the loop syntactically.
7) In Java, it is possible to create an infinite loop out of while and do loops, but not for-loops.
Answer: FALSE
Explanation: It is true that while and do loops can be infinite loops, but it is also true that Java for-loops can be infinite loops. This is not true in many other programming languages where for-loops have a set starting and ending point, but Java for-loops are far more flexible than most other language's for-loops.
8) A dialog box is a device which accepts voice commands.
Answer: FALSE
Explanation: A dialog box is a graphical window that pops up so that the user can interact with it.
7 Copyright © 2012 Pearson Education, Inc.
6.3 Free-Form Questions
1) Rewrite the following nested if-else statement as an equivalent switch statement. if (letter == 'A' | | letter == 'a') System.out.println("Excellent"); else if (letter == 'B' | | letter == 'b') System.out.println("You can do better"); else if (letter == 'C' | | letter == 'c') System.out.println("Try harder");
else if (letter == 'D' | | letter == 'd') System.out.println("Try much harder");
else System.out.println("Try another major! ");
Answer: switch (letter)
case 'A', 'a' : System.out.println("Excellent"); break; case 'B', 'b' : System.out.println("You can do better"); break; case 'C', 'c' : System.out.println("Try harder"); break; case 'D', 'd' : System.out.println("Try much harder"); break; default : System.out.println("Try another major! ");
2) Given the following tax table information, write Java code to assign the double taxRate appropriately given the double pay. Select the selection statement (if, if-else, switch) that makes the most sense.
If pay is more than 100,000, tax rate is 40%
If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30%
If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20%
If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10%
If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5%
If pay is less than or equal to 5,000, tax rate is 0%
Answer: Use a nested if-else structure as it requires the least amount of code. A switch statement is not possible because pay is a double and the switch statement can only be used for integral types.
if (pay > 100000)
taxRate = 0.40;
else if (pay > 60000)
taxRate = 0.30;
else if (pay > 30000)
taxRate = 0.20;
else if (pay > 15000)
taxRate = 0.10;
else if (pay > 5000)
taxRate = 0.05;
else
taxRate = 0.0;
8 Copyright © 2012 Pearson Education, Inc.
{
}
3) Show the output that would occur from the following code, including proper spacing. for (j = 0; j < 5; j++) { for (k = 0; k < 5; k++) if (j!=k)
System.out.print(' '); else System.out.print('*'); System.out.println( ); }
Answer: *
The outer loop iterates from 0 to 4, and for each iteration, the inner loop also iterates from 0 to 4. For iteration of the inner loop, if j and k are not the same, a blank is output, otherwise an *. So, if j = 0 and k = 2, then two blanks are output before an *, followed by two more blanks. At the end of each iteration of the inner loop, the cursor is returned to start a new line.
4) How many times will the System.out.println(*); statement execute inside of the following nested for-loops? for (j=0; j<10; j++) for (k=10;k>j;k ) System.out.println("*");
Answer: 55
Explanation: The first iteration of the outer loop has j = 0, so the inner loop iterates from 10 down to 1, or 10 times. The next iteration of the outer loop has j = 1, so the inner loop iterates from 10 down to 2, or 9 times. This continues until the outer loop has j = 9, in which case the inner loop iterates for k =10 only, or 1 time. Thus, the System.out.println statement executes a total of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 times.
5) Write a "query-controlled" loop that will continue to input int values from the user, adding each to the int value sum, and then ask if the user has another value to input, until the user says that there are no more values. Assume that cs1.Keyboard has been imported.
Answer: int x, sum = 0; String query; do {
System.out.println("Enter an int value to be summed");
x = Keyboard.readInt( ); sum += x;
System.out.println("Do you have any more ints to input? (Yes or No) "); query = Keyboard.readString( ); } while (query.equalsIgnoreCase("Yes"));
9 Copyright © 2012 Pearson Education, Inc.
* * * *
6) Write some code that inputs a set of int values and computes its average. Ask the user first how many int values will be input. Make sure that your code cannot produce a division by zero error. Assume that cs1.Keyboard has been imported.
Answer: int numberOfValues, j, current, sum = 0; System.out.println("Enter the number of ints you will be inputting"); numberOfValues = Keyboard.readInt( ); for (j = 0; j < numberOfValues; j++) {
System.out.println("Enter your next int value"); current = Keyboard.readInt( ); sum += current; }
if (numberOfValues != 0) double average = sum / numberOfValues; else System.out.println("Cannot compute the average of 0 values");
7) A data verification loop is a loop that asks the user to input a value within a restricted range repeatedly until the user has input a value within the requested range. Write a data verification loop that that inputs an int value x within the range 0 and 100. Assume cs1.Keyboard has been imported.
Answer: int x; do {
System.out.println("Enter an int value between 0 and 100"); x = Keyboard.readInt( ); } while (x >= 0 && x <= 100);
8) Describe a situation where you should use a do loop and a situation where you should use a while loop.
Answer: The do loop is used if you want to execute the loop body at least one time. This is useful for data verification (asking the user for a value, and only if the user has entered an improper value does your code repeat and try again). A while loop does not necessarily execute if the loop condition is not initially true. This might be useful if you want to control entrance to a loop such as only trying to sum up a list of values if the user actually has values to sum up.
9) Rewrite the following if-else statement using a conditional operator. if (x > y) z = x; else z = y;
Answer: z = (x > y) ? x : y;
10 Copyright © 2012 Pearson Education, Inc.
10) Write a paint method to draw out an American flag. The flag will comprise a blue square in the upper left corner and 13 red and white stripes, starting with red, and alternating. 6 of the 13 stripes appear to the right of the blue square and the last 7 stripes appear beneath the blue square extending as far right as the other stripes. Use a for-loop to draw the stripes. Do not try to draw any stars in the blue square.
Answer: public void paint(Graphics page)
page.setColor(Color.blue); page.fillRect(0, 0, 60, 60); for (int j = 0; j < 13; j++)
if (j % 2 == 0) page.setColor(Color.red); else page.setColor(Color.white); if (j < 6) page.fillRect(60, j * 10, 70, 10); else page.fillRect(0, j * 10, 130, 10);
11) The following for-loop is odd in that the loop increment value changes during iterations of the loop. Determine the number of times the loop iterates and the final value of j after the loop terminates.
int k = 0; for (j = 0; j < 20; j += k) k++;
Answer: 6 times with j = 21. Explanation: The first iteration has j = 0, k is then incremented in the loop body to 1 and j is incremented after the loop body executes to be j + k = 0 + 1 = 1. For the second iteration, k is incremented to 2 and j is incremented to j + k = 1 + 2 = 3. For the third iteration, k is incremented to 3 and j is incremented to 3 + 3 = 6. For the fourth iteration, k is incremented to 4 and j is incremented to 6 + 4 = 10. For the fifth iteration, k is incremented to 5 and j is incremented to 10 + 5 = 15. For the sixth iteration, k is incremented to 6 and j is incremented to 15 + 6 = 21. Now, since (j < 20) is no longer true, the loop terminates.
12) Write a set of code that outputs all of the int values between 1 and 100 with 5 values per line, and each of those 5 values spaced out equally. Use a single for-loop to solve this problem.
Answer: for (int j = 1; j <= 100; j++)
System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( );
11 Copyright © 2012 Pearson Education, Inc.
{
{
} }
{
}
13) The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0) ; x++; else x ;
Answer: The error is "else without if" and it arises because of the ";" after the condition but before x++. The Java compiler determines that the if clause is in fact ; (no statement) and that x++; is a statement that follows the if statement. Therefore, since x++; is not part of the if statement, the "else" is felt to be an else without an if, and that is why the error has arise. The statement should be if (x < 0) x++; else x ;
12 Copyright © 2012 Pearson Education, Inc.
Test Bank for Java Software Solutions: Foundations of Program Design, 7/E 7th Edition John Lewis, Visit TestBankBell.com to get complete for all chapters