xhtml
 

Multiple Tests

If you have several tests to do, where each is in the else part of the previous one, the result looks quite ugly, with lots of brackets and code which straggles off to the right

For example, if you want to test a string variable called op to see if it is one of the four standard arithmetic operators, you might end up with code like this:

if (op.equals("+"))
{
   ...
}
else
{
   if (op.equals("-"))
   {
      ...
   }
   else
   {
      if (op.equals("*"))
      {
         ...
      }
      else
      {
         if (op.equals("/"))
         {
            ...
         }
         else
         {
            ...
         }
      }
   }
}

It is conventional to neaten this up. Whenever an else clause contains nothing but another if, it can be treated as another test at the same level. The example above becomes:

if (op.equals("+"))
{
   ...
}
else if (op.equals("-"))
{
   ...
}
else if (op.equals("*"))
{
   ...
}
else if (op.equals("/"))
{
   ...
}
else
{
   ...
}

Back