If (expression) Else Code Segments

 

Introduction.  In the last webpage we developed If (expression) code segments.  But clearly, these are not sufficient for all situations.  For example, we didn't have any obvious ways to deal with users that didn't enter numbers in the correct range.  These users didn't get any interaction from the program.

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

if (expression)

{

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

}

else

{

program statements
that are executed if
(expression) is false;

}

 

 

This syntax augments what we had previously

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

if (expression)

single program statement when (expression) is true;

else

single program statement when (expression) is false;

This isn't really any different than the If - Then- Else statements used in Visual Basic except in VB you don't need to enclose the condition in parentheses and multiple program statements within the decision block are terminated by an End If.

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

if (userAge >= 18)

{

user can serve in military
user can vote
user can't drink

}

else

{

user can't vote
user can't drink
user might be able to drive

}
 

Another example might be

if (availableCredit > itemPrice)

buyer can buy;

else

buyer can't buy;

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

A Simple Code Example.  Now I want to slightly modify the NumberRangeApplet from the last web page to give some feedback to a user who incorrectly enters a number.  You should call the applet NRangeElseApplet.java.

 

import javax.swing.JOptionPane;
import javax.swing.JApplet;

public class NRangeElseApplet extends JApplet
{

public void init()
{

String userEntry;
float floatUserEntry = 0;

// Prompt user for input
userEntry = JOptionPane.showInputDialog("Please enter a number between 10 and 20:");

// convert these string values to integers
try
{

floatUserEntry = Float.parseFloat(userEntry);

}

catch (NumberFormatException nfeFloat)
{

JOptionPane.showMessageDialog( null, "The entry needs to be a number",
"Not a Number", JOptionPane.INFORMATION_MESSAGE);

}

if ((floatUserEntry > 10) && (floatUserEntry < 20))

// dislplaying a message with a MessageDialog
JOptionPane.showMessageDialog( null, "You entered " + floatUserEntry +
"\n which is between 10 and 20", "Valid Entry", JOptionPane.INFORMATION_MESSAGE);

else

JOptionPane.showMessageDialog( null, "You entered " + floatUserEntry +
"\n which is not between 10 and 20\n NOT PARTICAULARLY IMPRESSIVE!", "Invalid Entry", JOptionPane.INFORMATION_MESSAGE);
 

} // end method init

} // end class NumberRangeApplet

 

The html file should be NRangeElseApplet.html.

 

<APPLET CODE="NRangeElseApplet.class" WIDTH=200 HEIGHT=100> </APPLET>

 

Make sure you try entering a number of different values by using the restart option in the drop down box on the applet window.

Now we will revisit another one of our earlier examples.

Accumulating an Error Message.  When we first implemented try and catch blocks for numeric inputs we ended the program as soon as a user made an error.  This would be better if

  • we got all of the inputs from the user
  • put together an error message according to their errors
  • displayed the error message if they have made errors
  • ran the code if they don't have any input errors

So we will modify our earlier code into the following application called FloatFormatExceptions.java.

 

import javax.swing.JOptionPane;

public class FloatFormatExceptions
{

public static void main( String args[] )
{

String firstUserEntry, secondUserEntry;
float firstNumber = 0;
float secondNumber = 0;
float result;
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 == "")
{

result = firstNumber * secondNumber;

JOptionPane.showMessageDialog( null, "The product of the values you entered " + firstNumber +
" and " + secondNumber + " is " + result, "Float Product", JOptionPane.INFORMATION_MESSAGE);

}
else
{

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

}

System.exit(0);

} // end method main

} // end class NumberFormatExceptions

 

The code can be considered to be in five major sections
  • the initial section of code for
    • importing the JOptionPane class from the swing package
    • declaring the overall inclusive class
    • declaring the init( ) method
    • declaring and initializing variables
      • initializing an errorMessage as blank
  • the second section is for obtaining the inputs from the user via InputDialog boxes
  • the third section tries to parse the first input
    • if it fails then an appropriate message with appropriate control characters is appended to the overall errorMessage
  • the fourth section of code tries to parse the second input
    • if it fails then an appropriate message with appropriate control characters is appended to the overall errorMessage
  • the last section contains the if (expression) else block
    • if the errorMessage is still blank because no invalid entries were given then
      • the solution is computed and displayed
      • the inputs are echoed
    • if the errorMessage is not blank
      • the errorMessage is displayed using the else part of the code block

Now we will move onto one other even somewhat more complicated decision control structure in the  next webpage.