Java Decision Structures                 

   Contact
   C
   C++
   Visual Basic
   Java
   JavaScript
   DHTML
   Style Sheets
   About
   Normalization
   Active X
   TDC Binding
   PHP
   Perl and CGI
   Flash
   XML
   SQL
   Chat
   MCSE
   Linux
   Cabling   
 

   
 
    
    
Java 2  Java 3  Supplementary  Events  AWT Project  AWT Project  Language  Swing  Sound/Images

In any programming language decision structures are necessary. Decision structures allow your programs to make
decisions based upon user input or the results of a process. Java contains if/else and switch structures, as in C++.
They follow the general principles of logic, and in addition to employing relational and mathematical operators, they
also employ logical operators.  Logical operators allow more than one relational expression to be evaluated at a time,
allowing for a greater complexity of decisions as bits can be "AND'd" and "OR'd" together :)

if statement - enable testing for a condition and branching to different parts of code depending on the result.   The syntax is as following:

if(expression)
     statement;

else clause - makes code more easily readable, program follows one branch of code if the condition is true and another branch of code if it is false.  Syntax is as follows:

if(expression)
    statement;
else
    statement;

Example 1:

import javax.swing.*;

public class DecideStuff
{
      public void main(String[] args)
      {
             int FirstNumber = 0;
             int SecondNumber = 0;
 
            
FirstNumber = Integer.parseInt
             (JOptionPane.showInputDialog
             (null, "Enter a larger number:"));
 
             SecondNumber = Integer.parseInt
             (
JOptionPane.showInputDialog
             (null,
"Enter a smaller number:"));

 
             if(firstNumber > secondNumber)
             {  
               
JOptionPane.showMessageDialog
                (null,
"The 1st number is greater.");                

             }
             else
             {
                JOptionPane.showMessageDialog
                (null,
"The 2nd number is greater.");

             }

             System.exit(0);

      }//close main() function
 
}//close DecideStuff class

Notice: "JOptionPane.showInputDialog" returns a string and may be used to ask a question and take input from the user. "JOptionPane.showMessageDialog" may be used for output, it does not take input. Braces may be used to clarify a decision
structure, and are imperative if there is more than one line of code beneath an if or an else.

Output =
Please enter a big number:  10
Please enter a smaller number: 12
Oops.  The second is bigger!

Example 2:

import javax.swing.*;
import java.io.*;

public
class DecideStuff
{
      public void main(String[] args)
      {
             int FirstNumber = 0;
             int SecondNumber = 0;
             String choice = "";

 
                 LineNumberReader cin = new LineNumberReader
             (new InputStreamReader(System.in));
 

             System.out.print("\nEnter a larger number: ");
             try { choice = cin.readLine(); }
             catch(IOException e) { System.err.println("Error.");

             FirstNumber =
Integer.parseInt(choice);
 
             System.out.print("\nEnter a smaller number: ");
             try { choice = cin.readLine(); }
             catch(IOException e) { System.err.println("Error.");

             SecondNumber =
Integer.parseInt(choice);

 
             if(firstNumber >= secondNumber)
             {  
                 System.out.println(
"The 1st number is greater."); 
               
                 if
(firstNumber == secondNumber)
                 {
                    System.out.println("\nThey are equal.");
                 }
                 else
                 {
                    System.out.println("\nThey are not equal.");
                 }
  
             }
             else
             {
                 System.out.println("The 2nd number is greater.");
             }

             System.exit(0);

      }//close main() function
 
}//close DecideStuff class

Notice: The console is used for input and output, not JOptionPanes. To do this, we had to create a LineReader object. This object
must be placed in try/catch blocks where input is received. The input received from the LineNumberReader object, like the JOptionPane objects above, is a string. Therefore, we must also pass the value to "Integer.parseInt()". We use "System.out.print" and "System.out.println" to display output to the console. In addition, our if/else structures are nested.


switch(case) statement
- A switch statement is a decision structure possessing a default and several cases. 
Switch structures allow you to branch off on any of a number of different values.  "if" and "else...if" combinations can become confusing when nested too deeply.   The switch statement evaluates "expression" and compares the result to each of the case values.  The evaluation is ONLY for equality.  Relational operators (<>) and Boolean expressions can not be used here.  If one of the case values matches the expression, execution jumps to those statements and continues to the end of the switch block unless a break statement is encountered.  If nothing at all matches, execution branches to the "default" statement.  If there is no default statement and there is no matching value, execution falls through the switch statement and the statement ends.  You should always include a default case in switch statements, if only to render an error message.

Note: If there is no break statement at the end of a case statement, execution will fall through to the next case.  This is sometimes necessary or what you want as in the MFC, but many times it is an error.  If you do decide to let execution fall through, you might consider placing a comment indicating your intention and that you simply didn't just forget the "break" statement.  Example:

public class DecideStuff
{
      public void main(String[] args)
      {
             int Number = 0;
             String choice = "";

 
                 LineNumberReader cin = new LineNumberReader
             (new InputStreamReader(System.in));

 
             System.out.print("\nEnter a smaller number: ");
             try { choice = cin.readLine(); }
             catch(IOException e) { System.err.println("Error.");

             Number =
Integer.parseInt(choice);

 
             switch(Number)
             {
                  case 0 : RunProgram = 0;
                           break;
                  case 1 : cout << "You chose 1";
                           break;
                  case 2 : cout << "You chose 2";
                           break;
                  case 3 : cout << "You chose 3";
                           break;
                  case 4 : cout << "You chose 4";
                           break;
                  case 5 : cout << "You chose 5";
                           break;
                  case 6 : cout << "You chose 6";
                           break;
                  case 7 : cout << "You chose 7";

                           break;
                  default : cout << "Sorry, invalid choice.";
                            break;

             } //close switch statement


             System.exit(0);

      }//close main() function
 
}//close DecideStuff class

Notice: The switch statement is easier to follow than a bunch of nested if/else statements. Still, there are some situations that demand if/else statements. You can not switch on a string for each case, but you may compare string with "equals" and if/else. In a similar fashion, you can not use complex operational expressions and comparisons with switch statements  the way you can with if/else. You may pass a char into a switch statement also:

public class DecideStuff
{
      public void main(String[] args)
      {
             char Option = 0;
             String choice = "";

 
                 LineNumberReader cin = new LineNumberReader
             (new InputStreamReader(System.in));

 
             System.out.print("\nEnter a smaller number: ");
             try { choice = cin.readLine(); }
             catch(IOException e) { System.err.println("Error.");

             Option =
choice.charAt(0);
 
             switch(Option)
             {
                  case 'a' : RunProgram = 0;
                           break;
                  case 'b' : cout << "You chose b";
                           break;
                  case 'c' : cout << "You chose c";
                           break;
                  case 'd' : cout << "You chose d";
                           break;
                  case 'e' : cout << "You chose f";
                           break;
                  case 'f' : cout << "You chose f";
                           break;
                  case 'g' : cout << "You chose g";
                           break;
                  case 'h' : cout << "You chose h";

                           break;
                  default : cout << "Sorry, invalid choice.";
                            break;

             } //close switch statement


             System.exit(0);

      }//close main() function
 
}//close DecideStuff class

Notice: The LineNumberReader object returns a string from the user, so we must use a new function, "charAt()", to grab the
very 1st character of the string. This char can be passed to the switch and each case evaluated (with single quotes, not double).
Alternatively for a char, there is a "System.in.read()" function.

Operator Symbol Example
   AND    &&    expression1 && expression2
   OR     ||    expression1 || expression2 
   NOT         !       !expression

logical AND = Evaluates two expressions.  If both expressions are true the AND statement is true.  If one or both expressions are false the AND statement is false.  Example:  if ( (x == 5)  &&  (y == 5))  would evaluate true if both x and y are 5.

logical OR = If either expression is true, the OR statement is true.  Example:
if ( (x == 5)  ||  (y == 5)) would evaluate true if either x OR y is equal to 5.

logical NOT= Evaluates true if the expression being tested is FALSE.  If the expression being tested is false, the value of the test is true:
if ( !(x == 5) ) is true only if x is not equal to 5.  You could also write:    if (x  != 5).

Relational Precedence - Relational operators and logical operators each return 1 (true) or 0 (false).  They have a precedence order that determines which relations are evaluated first.  Example:

if( x > 5  &&  y > 5  ||  z > 5)  is better rewritten with parentheses:    if( (x > 5)  &&  (y > 5  ||  z > 5)  )

More about truth and falsehood:
if (x)
     x=0
;

Can be read as "If x is true (has a non-zero value), set it to 0".  It would be clearer written as:
if (x != 0)
     x = 0;

So these two statements are also equivalent;
if (!x)     //if x is false (zero)
if (x == 0)    
 //if x is zero


Java 2  Java 3  Supplementary  Events  AWT Project  HOME  AWT Project  Language  Swing  Sound/Images