RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect03c
Nesting if-else

nesting if-elses

In our previous example for slicesReadyMsg, we handled zero as the same as any other plural. That was fine for a first attempt, but can we separately handle all three categories of 0, 1, and “more”, using just the syntax for if-else?

if (condition) {
  statements
  }
else {
  statements
  }
Yes:
 String slicesReadyMsg( String topping, int slicesReady ) {

    if (slicesReady == 1) {
      return "There is "
           + slicesReady
           + " piping hot slice of "
           + topping
           + " pizza, ready to eat!";
      }
    else {   // slicesReady isn't equal to 1
      if (slicesReady ==0) {
        return "We are momentarily out of " + topping + " pizzas.";
        }
      else {
        return "There are "
             + slicesReady
             + " piping hot slices of "
             + topping
             + " pizza, ready to eat!";
        }
      }
    }
Our page of syntax now includes several types of statements (any of which can be inside an if or else clause): It's worth mentioning specially, that indentation starts becoming extremely important, to people reading your programs: it would be very easy to mislead people about what your program is doing, by being careless about indenting. After all, we had an if-else statement inside of another else clause, but it could conceivably also be written inside the if clause. Curly-brackets tell the computer what contains what else, but indentation is what tells humans how the code is structured. (If your code makes me stop to think about whether its visual structure matches what it really does, you will lose points.)

This idea of nesting an if-else statment inside another else clause is actually very common; it happens whenever we need to choose between more than two equal options. While what we wrote makes sense, it's annoying for two reasons:

In response to these common concerns, Java includes a variant of the if-else statement, call the if-else-if statement. Here's an example:
/** Return a greeting, selected randomly from a list of several greetings.
 * @return A greeting (randomly selected, not necessarily uniformly).
 */
String greet() {
  int choice = (new java.util.Random()).nextInt(100);
  // We'll discuss the "new" statement later1; here's the upshot: the local variable 
  // 'choice' now stores a number in the interval [0,99], a.k.a. [0,100).
  
  if (choice < 30) {
    return "Hello.";
    }
  else if (choice < 33) {  
    return "Aloha.";
    }
  else if (choice < 50) {  
    return "Buenos dias, amigo/amiga.";
    }
  else if (choice < 99) {  
    return "Yo.";
    }
  else if (choice < 100) {  
    // Not an advisable greeting.  Use sparingly.
    return "I am a javabot: System dot out dot println open \"hello\" close.";
    }
  else {
    System.err.println( "This statement is unreachable (I hope)." );
    return "A dummy return-statement to satisfy the compiler";
    }


  // Is this line ever reached?  Why or why not?

  }
Some discussions:

Technicalities

  1. In an if-else statement, Java allows you to leave off the last else, if the curly-brackets would be empty. I suggest you don't do this; if the purpose of the entire if-else-if, is to initialize a variable, then every branch should initialize that variable, and similarly if the purpose of the statement entire is to return an answer, then every branch needs to return the answers. However, you will see other people write code which initializes a variable to a potentially-wrong value, and then go back and correct it when needed (which seems a bit sloppier than just initializing it to the correct value to start with):
      /** Given how many slices of (say) mushroom pizza are
       * currently available, create a nice tempting message
       * to advertise (shout out, or post, or put on a
       * LED sign...)
       * 
       * @param topping The type of pizza (e.g. "pepperoni")
       * @param piecesReady The number of currently ready-to-serve
       *    slices with the given topping.
       * @return A complete sentence describing the inventory.
       * For example:
       * inventoryMessage( "mushroom", 3 ) 
       *   = "There are 3 piping hot pieces of mushroom pizza, ready to eat!"
       */
      String slicesReadyMsg( String topping, int slicesReady ) {
        String verbForm  = "are";   // The correct verb for our result.
        String plurality = "s";  // The noun-suffix, correctly plural or singular.
        
        if (numInStock == 1) {
          verbForm = "is";
          plurality = "";
          }
    
        return   "There " + verbForm + " "
               + slicesReady +
               + " piping hot slices of "
               + topping + ("pizza" + plurality)
               + " in stock.";
        }
    
  2. Moreover, when there is only a single statement in the body, the book reveals that you can conceivably omit the curly-brackets. 3
    optional: The following explanation is optional, and will be skipped in lecture, as long as you read the concluding edict below.)
    Alas, omitting the brackets is bad for several reasons:
    1. It's fairly common that you decide later to go back and add something to the if- or else- case, and you end up adding the brackets later. Moreover, if you have several lines in a block and delete them down to just one, you'd want to delete the brackets to be consistent (and not cause readers to wonder if there is some unintentional bug).
    2. This usually leads to confusion though, and the book has to spend several minutes talking about dangling elses.
    3. Consider:
         if (numInStock == 1)
           verbForm = "is";
         else
           verbForm = "are";
         
      What if we go back, and decide to add the lines for plurality, but we forget to put in curly-braces?:
         if (numInStock == 1)
           verbForm = "is";
           plurality = "";    // DANGER, WILL ROBINSON!
         else
           verbForm = "are";
           plurality = "s";
         
      Java gives an error “else without an if” -- why? If we hadn't had any else statement at all, would we have caught our error?
Edict: Even if you have only one line in an if- or else- block, include curly-braces.
One exception:

1

Well, new is nothing too magical; it creates a particular instance of a class. In this case, the class isn't “PizzaServer” but “java.util.Random” (a longwinded name, indeed). And instances of this class can't be asked about pizzaArea, but they do know how to generate a nextInt randomly.

So far we have been making new instances in BlueJ by right-clicking on “new PizzaServer()” (or whatever our class is named), but “new” is actual Java code to do the same thing. Note that we could have even named this java.util.Random instance with a local variable, if we had wanted to:

    java.util.Random ro = new java.util.Random();
    int choice = ro.nextInt(100);
    
We'll talk more about new and local-variables-to-hold-instances in the following weeks, but all the fundamental concepts are in place!

     

2 So we could conceivably use a series of if statements (without else), rather than a big if-else. The second if statement is only reached when the first condition wasn't true (because in that case we'd return before ever reaching the second if condition).      

3So really, the actual syntax for Java's if-else statement is

if (statement)
  expression
else
  expression
This is actually a general case of the version-with-brackets, given in these notes. Why? Because along with assignment statments and return statements and if statements, there is a block statement, which looks like { statements… }.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Feb.05 (Tue)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme