C

Java: Introduction to Switch constructs

Author: Ronald S. Holland
at
Total Application Works




To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


    Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <html>
    <head>
    <title>C#: Table of Contents </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/Java/JAV_Switch.html">
    Switch construct </a>
    </table>
    </body>
    </html>
    Source code


Table of Contents

Java Resources

    Read Me First

    The JAV_Switch.zip file contains the following files:

    1. Switch.bat - this file contains the code that when clicked will ompile and run the main program (Switch.java)
    2. Switch.java - this file contains the main method code and is the entry point when the program is loaded into memory,
    3. JAV_Switch.html - is the tutorial that describes how to build the Switch program
      • Switch.java.

    Introduction

    This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on c# or programming. As we ease into c#, we will briefly discuss the if control structure. c# as a programming language is widespread and can be found on nearly all computers. In the next section, we will briefly describe control structures.

    What is Java technology and why do I need it?

    Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

    Is Java free to download?

    Yes, Java is free to download. Get the latest version at java.com.

    Why should I upgrade to the latest Java version?

    The latest Java version contains important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing this free update will ensure that your Java applications continue to run safely and efficiently.

    Control Structures

    Bohm and Jacopini demonstrated, in their Structured program theorem, that all programs could be written using just three control structures.

    • sequence structure
        Consider the following example:

        
        int a = 8 , b ;
        b = (5 + 2) * a  ;
        cout << b << endl ;
        
        Figure 1: Squence of statements structure
        If a code snippet consists of the above three statements, then the statements will execute in the order/sequence that they are listed. This is also known as an ordered execution of statements.
    • selection structure
        In a selection statement, one of a number of statements is executed depending on the state of the program. Consider the following example:

        
        int a, b = 0;
        
        cout << "Enter a number less than 10 and greater than 0." << endl ;
        cin >> a ;
        
        if( a > 5 )
           b = (5 + 2) * a  ;
        
        cout << "The value of b is " <<  b << endl ;
        
        Figure 2: selection structure
    • repetition structure
        A repetition structure is used when a set of instructions need to be executed more than once.

        
        int b = 0;
        
        for( int ii = 0 ; ii < 10 ; ii++ ) {
           b = (5 + 2) * ii  ;
           cout << "The value of b is " <<  b << endl ;
        }
        
        Figure 3: repetition structure
    Control Structures or constructs are described further in the next section.

    Control Structures or constructs

    What are Control Structures or constructs? The Control Structures constructs used in programming are:
    1. if - single selection structure
        This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken.
        
        if( condition is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 4: if - single selection structure


    2. if/else - double selection structure
        This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken; otherwise, a different action is taken.
        
        if( condition is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        else {
           statements
        }
        
        Figure 5: if/else - double selection structure


    3. switch - multiple selection structure
        This structure allows selection among multiple sections of code, depending on the value of an integral expression. It operates much like a nested if construct.
        
        switch( expression ) {
           case 1;
              do something ;
           case 2;
              do something ;
           case 3;
              do something ;
           ...
        
           default;
              do something ;
        }
        
        Figure 6: switch - multiple selection structure


    4. while
        In this construct, the condition is a boolean statement that is checked after the final } braces of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the statements inside the while construct do not execute again, due to the code branching out of the construct.
        while( condition  is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 7: while loop structure


    5. do/while
        The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. This construct guarantees that the body of the loop always executes at least one time. The format of the do-while loop is shown below.
        do {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        while( condition is true )
        
        Figure 8: do-while loop structure


    6. for
        Executes the statements and loop-expression repeatedly until test becomes false. After the first pass, the loop counter is updated and then the test-condition is checked to determine whether it is true or false.
        for( initialization ; test ; update ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 9: for loop structure


    For the remainder of this tutorial, we will describe the if contruct.

    The if selection construct

    How do we use the if selection construct? In the real world, we often use the if selection construct, during the day. A teacher must decide at the end of the semester who gets a passing grade. What criteria is used? The criteria used is: if a student's grade is greater than or equal to 60 they enter a passing grade.

    Flowchart
    
                   _
                  ( )               
                   |
                   -          +--------------+
                  /g\  true   |   Email      |
                 />= \________|              |
                 \60 /        |   'passed'   |
                  \ /         +--------------+
                   -                |
        false -->  |                |
                   |<---------------+
                   V
                   -
                  ( ) 
    
    
    
    
     
    
           Decision symbol    Processing symbol
                   +                  +
                   |                  |
                   V                  V
                   -           +--------------+
                  / \          |              |
                 /   \         |              |
                 \   /         |              |
                  \ /          +--------------+
                   -                 
    
    
     The Decision symbol is used when a decision 
         needs to be made or evaluated
    
     The Processing symbol is used when processing 
         a sequence of needs to be made
      
    Pseudocode
              if grade is greater than or equal to 60 
                 email "passed" to the student
    
    Figure 11: if construct

    Without a conditional statement such as if, programs would run practically same way every time. The if statements allow the flow of a program to be altered.

    The if/else selection structure

    In this section, we descibe the The if/else selection structure, in terms of the following:

    1. Pseudocode
    2. The conditional operator ? :, and
    3. nested ifs


    Pseudocode
     
    
       if a student's grade is greater than or equal to 60
           print "passed"
       else
           print "failed" 
    
    
    
      
       
                        _
                       ( )               
                        |
    +---------+         ^          +--------------+
    | print   | false  /g\ true    |   print      |
    |         |<----- />= \________|              |
    | "failed"|       \60 /        |   'passed'   |
    +---------+        \ /         +--------------+
         |              v                |
         |              |                |
         +------------->|<---------------+
                        V
                        _
                       ( ) 
                        -
    
    
      
       
              if (grade >= 60) 
                 cout << "Passed" << endl;
              else 
                 cout << "Failed" << endl;
      
    conditional operator ? :
       
    cout <<  (grade >= 60 ? "Passed" : "Failed" ) << endl;
    
       --- or  ----
    
    cout <<  grade >= 60 ? cout << "Passed\n" : cout << "Failed\n"  ;
      
    nested ifs
       
              if (grade >= 90) 
                 cout << "A" << endl;
              else if (grade >= 80) 
                 cout << "B" << endl;
              else if (grade >= 70) 
                 cout << "C" << endl;
              else if (grade >= 60) 
                 cout << "D" << endl;
              else  
                 cout << "F" << endl;
    
     
    Figure 12: nested if/else selection structure


    An example of a The if selection construct program will be depicted in the next section.

    The if selection construct program

    In the following table, we show the code for an if selection construct program.

     
    /** **************************************************************************
     * This program averages 4 test scores. The If_Construct.cpp:
     *  1- Obtains four numbers from the user;
     *  2- Calculates the average of those four numbers;
     *  3- Prints the average to the screen.
     ***************************************************************************/
    
    
    using System ;
    
    /** ***************************************************
     * _tmain() method defines the C# entry point for the 
     *  console application that is used when the program is 
     *  loaded into memory. 
     *
     ******************************************************/
       public static void main( String args[] )  {
    	int Score1, Score2, Score3, Score4 ;
    	double average;
    
    
    	for ( int ii = 0 ; ii < 4 ; ii++ 0  ) {
               Console.WriteLine( "Enter a test score and they will be averaged: " ) ;
    	   score + "ii+1" = Console.ReadLine() ;
    	}
    
    	average = (Score1 + Score2 + Score3 + Score4) / 4.0;
    
    	cout.precision(1);
    	cout.setf(ios::showpoint | ios::fixed);
    	Console.WriteLine( "Your average is " + average + "\n" ) ;
    	if (average == 100)
    	   Console.WriteLine( "Congratulations! You've achieved a perfect score!\n" ) ;
    
    	return 0;
    }
    
     
    Figure 13: Single selection structure

    The if/else nested selection construct program

    In this section, we will show the nested if in the table below.

     
    /** **************************************************************************
     * This program averages 4 test scores using a nested if construct. This 
     * program does the following:
     *  1- Obtains four numbers from the user;
     *  2- Calculates the average of those four numbers;
     *  3- Prints the average to the screen.
     *  4- Prints the grade to the screen.
     ***************************************************************************/
    
    
    /** ***************************************************
     * main() method defines the C# entry point for the 
     *  console application that is used when the program is 
     *  loaded into memory. 
     *
     ******************************************************/
       public static void main( String args[] )  {
    	int Score1, Score2, Score3, Score4 ;
    	float average;
    
    	cout << "Enter 4 test scores and they will be averaged: ";
    	cin >> Score1 >> Score2 >> Score3 >> Score4 ;
    
    	average = (Score1 + Score2 + Score3 + Score4) / 4.0;
    
    	cout.precision(1);
    	cout.setf(ios::showpoint | ios::fixed);
    
    	if (average == 100)
               cout << "Congratulations! You've achieved a perfect score!\n";
    	else if (average >= 90) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "A" \n" << endl;
    	}
    	else if (average >= 80) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "B" \n" << endl;
    	}
    	else if (average >= 70) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "C" \n" << endl;
    	}
    	else if (average >= 60) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "D" \n" << endl;
    	}
    	else if (average < 60) {
               cout << "Your average is " << average << endl;
               cout << "Your grade is \"F\" \n" << endl;
    	}
    
    	system("Pause") ;
    
    	return 0;
    }
    
     
    Figure 14: nested if/else selection structure

    The switch statement is unlike the if-statement. It requires that each case be constant. For example:

     
    switch (expression) {
       case value1:
          statements;
       break;
       case value2:
          statements;
       break;
       default:
          statements;
       break;
    }
     
    Figure 15: switch structure
    • where value1 and value2 are typically int values.
    • The value specified on a case must be a constant of type int or must be able to be promoted to int (in other words a byte, short, int, or char).
    • The value of the case statement must either be a expression that is able to be evaluated to a constant
      e.g., 3 + 2.
    • hint: The case statements should be arranged in desending order of probability of occuring.
    This constraint allows various optimizations in the lower-level intermediate representation. Switch speeds up certain parts of a program.

    The problem with switch statements is essentially that of duplication. Often you find the same switch statement scattered around a program in different places. If you add a new clause to the switch, you have to find all these switch statements and change them.

    Calculate the number of days in a month

    Suppose you want to calculate the number of days in a month using a nested if and a switch construct>.

     
    import java.awt.*;
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane ;
    
    public class Switch2 {
    
       public static void main( String args[] ) {
    
    
          Calendar calendar = new GregorianCalendar();
          int month = calendar.get(Calendar.MONTH) + 1;
          int year = calendar.get(Calendar.YEAR) ;
          int numDays = 0 ;
    
          if( month == 1 || month == 3 || month == 5 || month == 7 ||
             month == 8 || month == 10 || month == 12 )  
        
             numDays = 31;
          else if( month == 4 || month == 6 || month == 9 || month == 11  )   
        
             numDays = 30;
    
          else if( month == 2 ) {
      
             if( ((year % 4 == 0) && !(year % 100 == 0))
                || (year % 400 == 0) )
    
                 numDays = 29;
             else
                numDays = 28;
          }
           
          
          JOptionPane.showMessageDialog(null, "Month =s " + month ,
                       "Press enter to continue", 
                       JOptionPane.INFORMATION_MESSAGE )    ; 
       }
    }
     
     
    import java.awt.*;
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane ;
    
    public class Switch {
    
       public static void main( String args[] ) {
    
    
          Calendar calendar = new GregorianCalendar();
          int month = calendar.get(Calendar.MONTH) + 1 ;
          int year = calendar.get(Calendar.YEAR) ;
          int numDays = 0 ;
    
          switch (month) {
             case 1:
             case 3:
             case 5:
             case 7:
             case 8:
             case 10:
             case 12:
                numDays = 31;
             break;
    
             case 4:
             case 6:
             case 9:
             case 11:
                numDays = 30;
             break;
    
             case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                   || (year % 400 == 0) )
                    numDays = 29;
                else
                   numDays = 28;
             break;
          } /*............. end of switch construct  */
    
           
          
          JOptionPane.showMessageDialog(null, "Month =s " + month ,
                       "Press enter to continue", 
                       JOptionPane.INFORMATION_MESSAGE )    ; 
       }
    }
     
    Figure 16: if and switch construct example

    • where new GregorianCalendar(edt) will return a zero for the month of January.




    HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


    To contact us

    © 2002 - 2016 All Rights Reserved Total Application Works