How to Use Fall-Through to Your Advantage in Java Programming - dummies

How to Use Fall-Through to Your Advantage in Java Programming

By Barry Burd

Often, when you’re using a switch statement in Java, you don’t want fall-through, so you pepper break statements throughout the switch. But, sometimes, fall-through is just the thing you need when programming with Java.

Take the number of days in a month. Is there a simple rule for this? Months containing the letter “r” have 31 days? Months in which “i” comes before “e” except after “c” have 30 days?

You can fiddle with if conditions all you want. But to handle all the possibilities=, you can use a switch statement.

import java.util.Scanner;
class DaysInEachMonth {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  int month, numberOfDays = 0;
  boolean isLeapYear;
  System.out.print("Which month? ");
  month = keyboard.nextInt();
  switch (month) {
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
   numberOfDays = 31;
   break;
  case 4:
  case 6:
  case 9:
  case 11:
   numberOfDays = 30;
   break;
  case 2:
   System.out.print("Leap year (true/false)? ");
   isLeapYear = keyboard.nextBoolean();
   if (isLeapYear) {
    numberOfDays = 29;
   } else {
    numberOfDays = 28;
   }
  }
  System.out.print(numberOfDays);
  System.out.println(" days");
  keyboard.close();
 }
}

For month number 6, the computer jumps to case 6. There are no statements inside the case 6 clause, so that part of the program’s run is pretty boring.

image0.jpg

But with no break in the case 6 clause, the computer marches right along to case 9. Once again, the computer finds no statements and no break, so the computer ventures to the next case, which is case 11. At that point, the computer hits pay dirt. The computer assigns 30 to numberOfDays, and breaks out of the entire switch statement.

February is the best month of all. For one thing, the February case in Listing 11-3 contains a call to the Scanner class’s nextBoolean method. The method expects you to type either true or false. The code uses whatever word you type to assign a value to a boolean variable.

image1.jpg

February also contains its own if statement. In February, you nest an if statement within a switch statement. That’s cool.