RU beehive logo ITEC dept promo banner
ITEC 120
2007fall
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect04a
Nesting if-else; connectives

An alternative to nesting: if-else-if

We saw last time that you can nest an if-else statment inside another else clause. The need for this 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:


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).      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Sep.16 (Sun)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme