Home

Conditional Statements

 

Introduction to Conditional Statements

 

Introduction

Imagine you are writing a program for the Motor Vehicle Administration. When processing a driver's license, you want to be able to ask an applicant if he or she wants to be an organ donor. This section of the program can appear as follows:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer;

        	System.out.print("Are you willing to be an organ donor? ");
	answer = in.readLine();
    }
}

The possible answers to this question are y, yes, Y, Yes, YES, n, N, no, No, NO, I don’t know, It depends, Why are you asking?, What do you mean?, What kind of organ are you referring to? What kind of person would possibly want my organ? Are you planning to sell my body parts?, etc. When you ask this type of question, make sure you let the applicant know that this is a simple question expecting a simple answer. For example, the above question can be formulated as follows:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);
    }
}

This time, the applicant knows that the expected answers are simply y for Yes or n for No.

 

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start the NetBeans IDE
  2. On the main menu, click File -> New Project...
  3. In the first page of the wizard, click General. In the Projects list, make sure that Java Application is selected and click Next
  4. In the Project Location, accept the suggested path or type a new one, such as C:\Programs\JavaLessons.
    In the Project Name text box, type MVA1 for a new application and click Finish
  5. Make changes to the file so it appears as follows:
     
    package MVA1;
    import java.io.*;
    
    public class Exercise {
        
        public static void main(String[] args) throws Exception
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String firstName, lastName;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name: " + firstName + " " + lastName);   
        }
    }
  6. Execute the application to test it. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Julienne
    Last Name:  Khan
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Julienne Khan

Boolean Variables

A variable is referred to as Boolean if it is meant to carry only one of two logical values stated as true or false. For this reason, such a variable is used only when testing conditions or when dealing with conditional statements.

To declare a Boolean variable, you can use the boolean keyword. Here is an example of declaring a Boolean variable:

boolean theStudentIsHungry;

After declaring a Boolean variable, you can give it a value by assigning it true or false. Here is an example:

package Exercise;

public class Exercise
{
    public static void main(String[] args)
    {
        	boolean theStudentIsHungry;

	theStudentIsHungry = true;
	System.out.print("The Student Is Hungry expression is: ");
	System.out.println(theStudentIsHungry);
	theStudentIsHungry = false;
	System.out.print("The Student Is Hungry expression is: ");
	System.out.println(theStudentIsHungry);  
    }
}

This would produce:

The Student Is Hungry expression is: true
The Student Is Hungry expression is: false

You can also give its first value to a variable when declaring it. In this case, the above variable can be declared and initialized as follows:

boolean theStudentIsHungry = true;
 

Practical Learning Practical Learning: Using a Boolean Variable

  1. To use an example of a Boolean variable, change the file as follows:
     
    package MVA1;
    import java.io.*;
    
    public class Exercise {
        
        public static void main(String[] args) throws Exception
        {
            	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName;
    	boolean isOrganDonor;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Are you willing to be an Organ Donor(y=Yes/n=No)? ");
    	String strOrganDonor = in.readLine();
    
            	if( strOrganDonor == "y" )
                		isOrganDonor = true;
            	else
                		isOrganDonor = false;
            
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name: " + firstName + " " + lastName); 
    	System.out.println("Organ Donor? " + isOrganDonor);  
        }
    }
  2. Execute the application to test it. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Patrick
    Last Name:  Mbouda
    Are you willing to be an Organ Donor(y=Yes/n=No)? n
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Patrick Mbouda
    Organ Donor? false
 

Formulations of Conditional Statements

 

if a Condition is True

One of the most regularly performed operations on a program consists of checking that a condition is true or false. When something is true, you may act one way. If it is false, you act another way. A condition that a program checks must be clearly formulated in a statement, following specific rules. The statement can come from you or from the computer itself. Examples of statements are:

  • "You are 12 years old"
  • "It is raining outside"
  • You live in Sydney"

One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write these statements and the computer only follows your logic). If a statement is true, the computer acts on a subsequent instruction.

The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is:

if(Condition) Statement;

If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:

Flowchart - If
 

If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked.

Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card number?". A source file of such a program could look like this:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	// Since the user is ready, let's process the credit card transaction
	if(ans == 1 ) System.out.print("\nNow we will get your credit card information.");
    }
}

Here is an example of running the program:

Are you ready to provide your credit card number(1=Yes/0=No)? 1

Now we will get your credit card information.

You can write the if condition and the statement on different lines; this makes your program easier to read. The above code could be written as follows:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	// Since the user is ready, let's process the credit card transaction
	if( ans == 1 )
            		System.out.print("\nNow we will get your credit card information.");
    }
}

You can also write the statement on its own line if the statement is too long to fit on the same line with the condition.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer, creditCardNumber;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	// Since the user is ready, let's process the credit card transaction
	if( ans == 1 )
        	{
	            System.out.println("Now we will get your credit card information.");
	            System.out.print("Please enter your credit card number without spaces: ");
	            creditCardNumber = in.readLine();
        	}
    }
}

If you omit the brackets, only the statement that immediately follows the condition would be executed.

 

Practical LearningPractical Learning: Using if

  1. To state an if condition, change the program as follows:
     
    package MVA1;
    import java.io.*;
    
    public class Exercise {
        
        public static void main(String[] args) throws Exception
        {
            	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName;
            	String strOrganDonor;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Are you willing to be an Organ Donor(y=Yes/n=No)? ");
    	strOrganDonor = in.readLine();
            
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name: " + firstName + " " + lastName); 
    	System.out.print("Organ Donor? ");
            	if( strOrganDonor == "y" )
                		System.out.print("Yes");
        }
    }
  2. Execute the application and test it as done previously

Otherwise: if…else

The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer an alternate statement in case the user provides another answer. Here is an example:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer, creditCardNumber;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	if( ans == 1 ) // First Condition
	{
            		System.out.println("\nThis job involves a high level of self-control.");
            		System.out.print("We will get back to you.\n");
	}
        	if( ans == 0 ) // Second Condition
            		System.out.print("\nYou are hired!\n");
    }
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? 1

This job involves a high level of self-control.
We will get back to you.

The problem with the above program is that the second if is not an alternative to the first, it is just another condition that the program has to check and execute after executing the first. On that program, if the user provides y as the answer to the question, the compiler would execute the content of its statement and the compiler would execute the second if condition.

You can also ask the compiler to check a condition; if that condition is true, the compiler will execute the intended statement. Otherwise, the compiler would execute alternate statement. This is performed using the syntax:

if(Condition)
    Statement1;
else
    Statement2;
Flowchart

The above program would better be written as:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer, creditCardNumber;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	if( ans == 1 ) // First Condition
	{
            		System.out.println("\nThis job involves a high level of self-control.");
            		System.out.print("We will get back to you.\n");
	}
        	else // Any Condition
            		System.out.print("\nYou are hired!\n");
    }
}
 

Practical LearningPractical Learning: Using if...else

  1. Make the following changes to the file:
     
    package MVA1;
    import java.io.*;
    
    public class Exercise {
        
        public static void main(String[] args) throws Exception
        {
            	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName, strOrganDonor, gender;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Gender(F=Female/M=Male): ");
    	gender = in.readLine();
    	System.out.print("Are you willing to be an Organ Donor(y=Yes/n=No)? ");
    	strOrganDonor = in.readLine();
            
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name: " + firstName + " " + lastName); 
            	System.out.println("Sex:         " + gender);
    	System.out.print("Organ Donor? ");
            	if( strOrganDonor == "y" )
                		System.out.print("Yes");
            	else
                		System.out.print("No");
        }
    }
  2. Execute the application and test it

The Ternary Operator (?:)

The conditional operator behaves like a simple if…else statement. Its syntax is:

Condition ? Statement1 : Statement2;

The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int number1, number2, maximum;
	String strNumber1, strNumber2;
	
        	System.out.print("Enter first numbers: ");
	strNumber1 = in.readLine();
	System.out.print("Enter second numbers: ");
	strNumber2 = in.readLine();
		
	number1 = Integer.parseInt(strNumber1);
	number2 = Integer.parseInt(strNumber2);
	maximum = (number1 < number2) ? number2 : number1;
	
	System.out.print("\nThe maximum of ");
	System.out.print(number1 + " and " + number2 + " is ");
	System.out.println(maximum);
    }
}

Here is an example of running the program:

Enter first numbers: 244
Enter second numbers: 68

The maximum of 244 and 68 is 244

Practical LearningPractical Learning: Using the Ternary Operator

  1. To use the ternary operator, change the file as follows:
     
    package MVA1;
    import java.io.*;
    
    public class Exercise {
        
        public static void main(String[] args) throws Exception
        {
            	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName, strOrganDonor, gender;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Gender(F=Female/M=Male): ");
    	gender = in.readLine();
    	System.out.print("Are you willing to be an Organ Donor(y=Yes/n=No)? ");
    	strOrganDonor = in.readLine();
            
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name: " + firstName + " " + lastName); 
            	System.out.println("Sex:         " + gender);
    	System.out.print("Organ Donor? ");
           	System.out.println(strOrganDonor == "y" ? "Yes" : "No");
        }
    }
  2. Save, compile, and test the file. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Sophia
    Last Name:  McCormack
    Sex(F=Female/M=Male): M
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Sophia McCormack
    Sex:         M
    Organ Donor? Yes
  3. Return to Notepad

Conditional Statements: if…else if and if…else if…else

The previous conditional formula is used to execute one of two alternatives. Sometimes, your program will need to check many more statements than that. The syntax for such a situation is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;

An alternative syntax would add the last else as follows:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else
    Statement-n;
if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else if(Condition3)
    Statement3;
else
    Statement-n;
 

The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means that you can include as many conditions as you see fit using the else if statement. After examining all the known possible conditions, if you still think that there might be an unexpected condition, you can use the optional single else.

A program we previously wrote was considering that any answer other than y was negative. It would be more professional to consider a negative answer because the program anticipated one. Therefore, here is a better version of the program:

package Exercise;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String answer, creditCardNumber;
        	int ans;
	
	// Request the availability of a credit card from the user
	System.out.print("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	answer = in.readLine();
        	ans = Integer.parseInt(answer);

	if( ans == 1 ) // First Condition
	{
        		System.out.println("\nThis job involves a high level of self-control.");
        		System.out.print("We will get back to you.\n");
	}
       	else if( ans == 0 ) // Alternative
		System.out.print("\nYou are hired!\n");
	else
		System.out.print("\nThat's not a valid answer!\n");
    }
}

You can also use the ternary operator recursively to process an if...else if condition.

Practical LearningPractical Learning: Using if...else if

  1. Change the file as follows:
     
    using System;
    
    class Exercise
    {
        public static void main(String[] args) throws Exception
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName;
    	String organDonorAnswer;
    	char sex;
    	String Gender;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Sex(F=Female/M=Male): ");
    	Sex = char.Parse(in.readLine());
    	System.out.print("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    	organDonorAnswer = in.readLine();
    
    	if( Sex == 'f' )
    	    gender = "Female";
    	else if( Sex == 'F' )
    	    gender = "Female";
    	else if( Sex == 'm' )
    	    gender = "Male";
    	else if( Sex == 'M' )
    	    gender = "Male";
    	else
    	    gender = "Unknown";
    
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name:   {0} {1}", firstName, lastName);
    	System.out.println("Sex:         {0}", Gender);
    	System.out.print("Organ Donor? ");
    	System.out.println(organDonorAnswer == "1" ? "Yes" : "No");
    
            	return 0;
        }
    }
  2. Save, compile, and test the file. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Helene
    Last Name:  Andong
    Sex(F=Female/M=Male): f
    Are you willing to be an Organ Donor(1=Yes/0=No)? 0
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Helene Andong
    Sex:         Female
    Organ Donor? No
  3. Return to Notepad
  4. To use a multi-ternary operator as if...else if, change the file as follows:
     
    using System;
    
    class Exercise
    {
        public static void main(String[] args) throws Exception
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName;
    	String organDonorAnswer;
    	char sex;
    	String Gender;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Sex(F=Female/M=Male): ");
    	Sex = char.Parse(in.readLine());
    	System.out.print("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    	organDonorAnswer = in.readLine();
    
    	if( Sex == 'f' )
    	    gender = "Female";
    	else if( Sex == 'F' )
    	    gender = "Female";
    	else if( Sex == 'm' )
    	    gender = "Male";
    	else if( Sex == 'M' )
    	    gender = "Male";
    	else
    	    gender = "Unknown";
    
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name:   {0} {1}", firstName, lastName);
    	System.out.println("Sex:         {0}", Gender);
    	System.out.print("Organ Donor? ");
    	System.out.println(organDonorAnswer == "1" ? "Yes" : (organDonorAnswer == "0" ? "No" : "Invalid Answer"));
    
            return 0;
        }
    }
  5. Save, compile, and test the application. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Patrick
    Last Name:  St-Eloi
    Sex(F=Female/M=Male): m
    Are you willing to be an Organ Donor(1=Yes/0=No)? 4
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Patrick St-Eloi
    Sex:         Male
    Organ Donor? Invalid Answer
  6. Return to Notepad

The switch Statement

When defining an expression whose result would lead to a specific program execution, a switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
}

The expression to examine is an integer. Since a character (char) is just another form of integer, it can be used too. Here is an example of using the switch statement:

package Exercise;
import java.io.*;

public class Exercise
{
    
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int number;
	String strNumber;
	
	System.out.print("Type a number between 1 and 3: ");
	strNumber = in.readLine();
	number = Integer.parseInt(strNumber);
	
	switch(number)
	{
            		case 1:
                		System.out.print("\nYou typed 1.");
            		case 2:
                		System.out.print("\nYou typed 2.");
           		case 3:
                		System.out.print("\nYou typed 3.");	
	}
    }
}

The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If he types 2, the program would execute the second and third cases. If he supplies 3, only the third case would be considered. If the user types any other number, no case would execute.

As mentioned for the if...else conditions, when using a switch statement, it is still possible that none of the choices of the available cases would be considered. The equivalent of a last else for a switch is created using a default section. This section starts with the default keyword. If you decide to include a default section, the formula of a switch statement becomes:

switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
    default:
        Default Statement;
}

With this formula, if none of the cases matches the selection, the statement(s) in the default section would execute. Here is an example:

package Exercise;
import java.io.*;

public class Exercise
{
    
    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int number;
	String strNumber;
	
	System.out.print("Type a number between 1 and 3: ");
	strNumber = in.readLine();
	number = Integer.parseInt(strNumber);
	
	switch(number)
	{
 	           case 1:
                	System.out.print("\nYou typed 1.");
	           case 2:
                	System.out.print("\nYou typed 2.");
 	           case 3:
                	System.out.print("\nYou typed 3.");	
	           default:
                	System.out.print("\nUnknown Option");
	}
    }
}

This is an example of running the program:

Type a number between 1 and 3: 6

Unknown Option
 

Practical LearningPractical Learning: Using a switch Statement

  1. Change the file as follows:
     
    using System;
    
    class Exercise
    {
        public static void main(String[] args) throws Exception
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            	String firstName, lastName;
    	String organDonorAnswer;
    	char sex;
    	String Gender;
    	char DLClass;
    	
    	System.out.println(" -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Application ---");
    	System.out.print("First Name: ");
    	firstName = in.readLine();
    	System.out.print("Last Name:  ");
    	lastName = in.readLine();
    	System.out.print("Sex(F=Female/M=Male): ");
    	Sex = char.Parse(in.readLine());
    	System.out.println(" - Driver's License Class -");
    	System.out.println("A - All Non-commercial vehicles except motorcycles");
    	System.out.println("B - Non-commercial vehicles up to and including 26,001/more lbs.");
    	System.out.println("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.");
    	System.out.println("K - Mopeds");
    	System.out.println("M - Motorcycles");
    	System.out.print("Your Choice: ");
    	DLClass = char.Parse(in.readLine());
    	System.out.print("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    	organDonorAnswer = in.readLine();
    
    	if( Sex == 'f' )
    	    gender = "Female";
    	else if( Sex == 'F' )
    	    gender = "Female";
    	else if( Sex == 'm' )
    	    gender = "Male";
    	else if( Sex == 'M' )
    	    gender = "Male";
    	else
    	    gender = "Unknown";
    
    	System.out.println("\n -=- Motor Vehicle Administration -=-");
    	System.out.println(" --- Driver's License Information ---");
    	System.out.println("Full Name:   {0} {1}", firstName, lastName);
    	System.out.println("Sex:         {0}", Gender);
    
    	switch(DLClass)
    	{
    	case 'a':
    	case 'A':
    	    System.out.println("Class:       A");
    	    break;
    	case 'b':
    	case 'B':
    	    System.out.println("Class:       B");
    	    break;
    	case 'c':
    	case 'C':
    	    System.out.println("Class:       C");
    	    break;
    	case 'k':
    	case 'K':
    	    System.out.println("Class:       K");
    	    break;
    	case 'm':
    	case 'M':
    	    System.out.println("Class:       M");
    	    break;
    	default:
    	    System.out.println("Class:       Unknown");
    	    break;
    	}
    
    	System.out.print("Organ Donor? ");
    	System.out.println(organDonorAnswer == "1" ? "Yes" : (organDonorAnswer == "0" ? "No" : "Invalid Answer"));
    
            	return 0;
        }
    }
  2. Save, compile, and test the application. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Hermine
    Last Name:  Schwartz
    Sex(F=Female/M=Male): F
     - Driver's License Class -
    A - All Non-commercial vehicles except motorcycles
    B - Non-commercial vehicles up to and including 26,001/more lbs.
    C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.
    K - Mopeds
    M - Motorcycles
    Your Choice: c
    Are you willing to be an Organ Donor(1=Yes/0=No)? 0
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Hermine Schwartz
    Sex:         Female
    Class:        C
    Organ Donor? No
  3. Return to Notepad
 

Previous Copyright © 2005 FunctionX. Inc. Next