If (expression) - Else If (expression) Code Segments

 

Introduction.  We are about to take another step in our capabilities to handle complex decisions.  In many instances there are many different options such as you say good morning if it is a time in a certain range, you say good afternoon for a different range of times and so on.

In order to move towards a more complete listing of options we need if (expression) else if (expression) control structures.

if (expression1)
{

program statements
that are executed if
(expression1) is true;

}

else if (expression2)
{

program statements
that are executed if
(expression2) is true;

}

. . .

else if (expressionN)
{

program statements
that are executed if
(expressionN) is true;

}

 

else
{

program statements
that are executed if
none of the previous
(expressions) is true;

}

 

 

This syntax augments what we had previously.  You do not need to include the final else segment.

If there is only a single code statement after any if (expression), else if (expression) and/or the else, there don't need to be any braces in that section of code.

Some Verbal Examples.  We will start with some relatively common language examples and then progress to computer code.

if ((0500 < timeOfDay) && (timeOfDay < 1200))
{

good morning

}

else if ((1200 <= timeOfDay) && (timeOfDay < 1800))
{

good afternoon

}

else if ((1800 <= timeOfDay) && (timeOfDay < 2200))
{

good evening

}

else
{

go to bed

}

 

Well, this can go on and on.  Obviously, some of these depend on having other sources for inputs.

A Simple Code Example.  Now I will present a simple application to obtain two numbers from a user and tell them which is greater than the other or whether they are equal.  You should call the file  NumberComparison.java.

 

import javax.swing.JOptionPane;

public class NumberComparison
{

public static void main( String args[] )
{

String firstUserEntry, secondUserEntry;
float firstNumber = 0;
float secondNumber = 0;
String errorMessage = "";

// Prompt user for input
firstUserEntry = JOptionPane.showInputDialog("Please enter a number:");
secondUserEntry = JOptionPane.showInputDialog("Please enter another number:");

// convert these string values to Floats
try
{

firstNumber = Float.parseFloat(firstUserEntry);

}

catch (NumberFormatException nfeFloat)
{

errorMessage = "You need to enter a number for the first entry\n";

}

try
{

secondNumber = Float.parseFloat(secondUserEntry);

}

catch (NumberFormatException nfeFloat)
{

errorMessage = errorMessage + "You need to enter a number for the second entry";

}

// compute solution if inputs are valid
// give error message if inputs are invalid

if (errorMessage == "")
{

if (firstNumber < secondNumber)

JOptionPane.showMessageDialog( null, "Your first entry " + firstNumber +
"\nis less than\nyour second entry " + secondNumber,
"First Less Than Second", JOptionPane.INFORMATION_MESSAGE);

else if (firstNumber > secondNumber)

JOptionPane.showMessageDialog( null, "Your first entry " + firstNumber + "\nis greater than\nyour second entry " + secondNumber,
"First Greater Than Second", JOptionPane.INFORMATION_MESSAGE);

else

JOptionPane.showMessageDialog( null, "Your first entry " + firstNumber + "\nequals your second entry " + secondNumber,
"First Equals Second", JOptionPane.INFORMATION_MESSAGE);

}
else
{

JOptionPane.showMessageDialog( null, errorMessage, "Input Error", JOptionPane.INFORMATION_MESSAGE);

}

System.exit(0);

} // end method main

} // end class NumberComparison

 

 

This code can be considered to be in three sections.  Though the last section has one decision control structure nested within another.
  • Import, declarations and initializations
    • it will be too repetitive to even describe
  • Obtaining inputs from user
    • making use of try and catch
    • accumulating an appropriate error message
  • Based on the errorMessage due to errors
    • if no errors
      • compare the two inputs using an if - else - else if structure
    • if errors
      • display the appropriate error message

The next webpage contains something analogous to this if-else-else if structure, but the conditions for determining which code segment executes is simpler.