Chapter 5


Exercise 1 Rewrite the following code to maximize readability:

switch (x) {   case 100:     System.out.println("x is big");     break;   case 101:     System.out.println("x is big");     break;   case 10:     System.out.println("x is medium");     break;   case -1000:     System.out.println("x is negative");     break; }

Solution 1 The 100 and 101 cases can be combined, and the cases can be arranged in ascending numerical order, to produce the following:

switch (x) {   case -1000:     System.out.println("x is negative");     break;   case 10:     System.out.println("x is medium");     break;   case 100:   case 101:     System.out.println("x is big");     break; }

Exercise 2 Rewrite the following code to make it cleaner:

boolean flag = false; switch (a) {   case 1:     x = 1000;     flag = true;     break;   case 30:     y = 1000;     flag = true;     break; } if (!flag)   z = 1000;

Solution 2 The flag just indicates that the switch has a case that matches its argument. So the "z = 1000" assignment happens only if there was no case to match the switch argument. We can eliminate the flag and move the "z = 1000" assignment into the switch's default case:

switch (a) {   case 1:     x = 1000;     flag = true;     break;   case 30:     y = 1000;     flag = true;     break;   default:     z = 1000;     break; }

Exercise 3 What happens when the following code is executed with val equal to 10? 100? 1,000? First, decide just by looking at the source code. Then write a program to verify your answer.

switch (val) {   case 10:     System.out.println("ten");   case 100:     System.out.println("hundred");   default:     System.out.println("thousand"); }

Solution 3 The code doesn't have any break statements, so every case will fall through to the next one. The output for 10 is

ten hundred thousand

The output for 100 is

hundred thousand 

And the output for 1000, which is handled by the default code, is

thousand

The following program verifies the results. Note the for loop, with multiple action in the update:

public class SwitchTest {   public static void main(String[] args)   {     int val = 10;     for (int i=0; i<3; i++, val*=10)     {       System.out.println("\nTesting " + val + " ... ");       switch (val)       {         case 10:           System.out.println("ten");         case 100:           System.out.println("hundred");         default:           System.out.println("thousand");       }     }   } }

Exercise 4 Run the WhileLab animated illustration by typing java loops.WhileLab. Try changing the value in the condition in the third line. What do you notice about the final value of a?

Solution 4 The final values of a are always square numbers.

Exercise 5 The description of WhileLab suggests three exercises, which are repeated here. For each desired result, configure the inputs of WhileLab to produce that result. Then verify your work (and make sure WhileLab is trustworthy) by writing an application that duplicates each while loop. The loops should generate the following results:

  • The sum of the numbers 1 through 500, inclusive.

  • The sum of the even numbers from 50 through 60, inclusive.

  • The product of the first 5 odd numbers.

Solution 5 The sum of 1 through 500:

int a = 0; int b = 1; while (b <= 500) {   a = a+b;   b = b+1; }

The sum of the even numbers from 50 through 60, inclusive:

int a = 0; int b = 50; while (b <= 60) {   a = a+b;   b = b+2; }

The product of the first 5 odd numbers (the nth odd number is 2n+1):

int a = 1; int b = 0; while (b < 5) {   a = a * (2*b+1);   b = b+1; }

Exercise 6 There is a number game called Hotpo that can entertain you for a few minutes while you're stuck in traffic, waiting for a movie to start, or having dinner with someone really boring. Hotpo stands for Half Or Triple Plus One, and it works like this: Think of an odd number. Now mentally calculate another number, as follows: If the first number was even, the next number is half the first one; if the first number was odd, the next number is 3 times the first number, plus 1. Now you can forget the first number and apply the Half Or Triple Plus One formula to your current number. Keep going until the value reaches 1. Let's try this with a starting number of 5. The series is 5 16 8 4 2 1. Write a program that plays Hotpo. First, initialize a variable called n to the starting value you're interested in. Then enter a loop that prints out each number in the sequence, along with the current step number. For example, the output for 3 would be

Step #1: 10 Step #2: 5 Step #3: 16 Step #4: 8 Step #5: 4 Step #6: 2 Step #7: 1

Should the program use a while loop or a for loop?

Solution 6 Hotpo is an extreme example of a situation that ought to use a while loop. Remember that for loops are better when you know beforehand how many passes you will make through the loop's body, and while loops are better when you don't know you're done until you're done. If you've played with various values of n, you may have noticed that there's no way to predict whether a certain starting value will need a lot of steps or only a few steps to reach 1. Hotpo defies mathematical analysis. There seems to be no way to predict how many steps a given starting value will require, which means a while loop is ideal. Here is a solution:

public class HotpoWhile {   public static void main(String[] args)   {     int n = 3;     int nSteps = 0;     while (n != 1)     {       n = (n%2 == 0) ? n/2 : 3*n+1;       nSteps++;       System.out.println("Step #" + nSteps + ": " + n);     }   } }

Note: If you're ever really bored, try 31.

Exercise 7 What is the value of n after the following code is executed?

int n = 1; outer: for (int i=2; i<10; i++) {     for (int j=1; j<i; j++)     {         n *= j;         if (i*j == 10)             break outer;     } }

Solution 7 The answer is 24, but the real question is: How did you arrive at the answer? The code is only 10 lines long, and four of those lines are just curly brackets, but the nested loops are intricate enough that working out the answer mentally or on paper is unreliable. It doesn't take long to just type in the code, let it run, and see what happens.




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net