Programming and Problem Solving with Java

(やまだぃちぅ) #1
469

4.How would you change the code you wrote for Question 3 so that it writes an
error message if the value is not 1 , 2 , or 3? (pp. 438–442)
5.What is the primary difference between a whileloop and a doloop? (pp.
442–445)
6.A certain problem requires a count-controlled loop that starts at 10 and counts
down to 1. Write the heading (the first line) of a forstatement that controls this
loop. (pp. 445–447)
7.What Java looping statement would you choose for a loop that is both count-
controlled and event-controlled and whose body might not execute even
once? (p. 448)
8.What is the difference between an expression and an expression statement in
Java? (pp. 448–450)

Answers



  1. try
    {
    intValue = Integer.parseInt("123");
    }
    catch(NumberFormatException except)
    {
    System.out.println(except.getMessage);
    }

  2. Throwable

  3. switch(nameVal)
    {
    case 1 : outData.println("Mary");
    break;
    case 2 : outData.println("Lynn");
    break;
    case 3 : outData.println("Smith");
    break; // Not required
    }

  4. switch(nameVal)
    {
    case 1 : outData.println("Mary");
    break;
    case 2 : outData.println("Lynn");
    break;
    case 3 : outData.println("Smith");
    break;
    default: outData.println("Invalid name value.");
    break; // Not required
    }

  5. The body of a doloop always executes at least once; the body of a whileloop may not execute at all.6.for
    (count = 10 ; count >= 1 ; count--)7.A while(or perhaps a for) statement 8. An expression becomes
    an expression statement when it is terminated by a semicolon.

Free download pdf