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 System.*;

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

		Console.Write("Are you willing to be an organ donor? ");
		answer = Console.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 System.*;

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

		Console.Write("Are you willing to be an organ donor (y=Yes/n=No)? ");
		answer = Console.ReadLine();

		return 0;
	}
}

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 Notepad and type the following:
     
    package GCS;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    
    	}
    }
  2. Save the file in a new folder named GCS2 inside your JSharp Lessons folder
  3. Save the file as Exercise.jsl in the GCS1 folder
  4. Start Visual Studio .NET and create a new Visual J# Console Application
  5. In the Name text box, type MVA1
  6. In the Location text box, type a path or select the folder we created in the previous lesson: C:\JSharp Lessons
  7. In the top section of the file, under the package line, type import System.*;
  8. From what we have learned so far, change the file as follows:
     
    package MVA1;
    import System.*;
    
    public class Exercise
    {
    	public static void main(String[] args)
    	{
    		String firstName, lastName;
    	
    		Console.WriteLine(" -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Application ---");
    		Console.Write("First Name: ");
    		firstName = Console.ReadLine();
    		Console.Write("Last Name:  ");
    		lastName = Console.ReadLine();
    
    		Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Information ---");
    		Console.WriteLine("Full Name: {0} {1}\n", firstName, lastName);
    	}
    }
  9. Execute the application and test it. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Jerry
    Last Name:  Moons
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Jerry Moons
    
    Press any key to continue
  10. Return to Notepad

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 bool 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 a true or false value. Here is an example:

package Exercise;
import System.*;

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

		theStudentIsHungry = true;
		Console.Write("The Student Is Hungry expression is: ");
		Console.WriteLine(theStudentIsHungry);
		theStudentIsHungry = false;
		Console.Write("The Student Is Hungry expression is: ");
		Console.WriteLine(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;
 

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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		char answer;
		String strAns;
	
		// Request the availability of a credit card from the user
		Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
		strstrAns = Console.ReadLine();
		answer = Char.Parse(strAns);

		// Since the user is ready, let's process the credit card transaction
		if(answer == '1') Console.WriteLine("\nNow 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 System.*;

public class Exercise
{
    public static void main(String[] args)
    {
	char answer;
	String strAns;
	
	// Request the availability of a credit card from the user
	Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	strstrAns = Console.ReadLine();
	answer = Char.Parse(strAns);

	// Since the user is ready, let's process the credit card transaction
	if(answer == '1')
		Console.WriteLine("\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 System.*;

public class Exercise
{
    public static void main(String[] args)
    {
	char answer;
	String strAns, creditCardNumber;
	
	// Request the availability of a credit card from the user
	Console.Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
	strstrAns = Console.ReadLine();
	answer = Char.Parse(strAns);

	// Since the user is ready, let's process the credit card transaction
	if(answer == '1')
	{
		Console.WriteLine("Now we will get your credit card information.");
		Console.Write("Please enter your credit card number without spaces: ");
		creditCardNumber = Console.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 System.*;
    
    public class Exercise
    {
    	public static void main(String[] args)
    	{
    		String firstName, lastName;
    		String strOrganDonor;
    	
    		Console.WriteLine(" -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Application ---");
    		Console.Write("First Name: ");
    		firstName = Console.ReadLine();
    		Console.Write("Last Name:  ");
    		lastName = Console.ReadLine();
    		Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    		strOrganDonor = Console.ReadLine();
    
    		Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Information ---");
    		Console.WriteLine("Full Name:   {0} {1}", firstName, lastName);
    		Console.Write("Organ Donor? ");
    		if( strOrganDonor.Equals("1") ) Console.Write("Yes");
    
    		Console.WriteLine();
    	}
    }
  2. Execute the application and test it. Here is an example:
     
    -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Catherine
    Last Name:  Wallington
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name:   Catherine Wallington
    Organ Donor? Yes
  3. Return to Notepad

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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		char answer;
		String strAns;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		strAns = Console.ReadLine();
		answer = Char.Parse(strAns);

		if( answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		if( answer == 'n' ) // Second Condition
			Console.Write("\nYou are hired!\n");
	}
}

Here is an example of running the program:

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

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

Press any key to continue

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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		char answer;
		String strAns;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		strAns = Console.ReadLine();
		answer = Char.Parse(strAns);

		if( answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		else // Second Condition
			Console.Write("\nYou are hired!\n");
	}
}
 

Practical LearningPractical Learning: Using if...else

  1. Make the following changes to the file:
     
    package MVA1;
    import System.*;
    
    public class Exercise
    {
    	public static void main(String[] args)
    	{
    		String firstName, lastName;
    		String strOrganDonor;
    		char gender;
    	
    		Console.WriteLine(" -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Application ---");
    		Console.Write("First Name: ");
    		firstName = Console.ReadLine();
    		Console.Write("Last Name:  ");
    		lastName = Console.ReadLine();
    		Console.Write("Gender(F=Female/M=Male): ");
    		gender = Char.Parse(Console.ReadLine());
    		Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    		strOrganDonor = Console.ReadLine();
    
    		Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Information ---");
    		Console.WriteLine("Full Name:   {0} {1}", firstName, lastName);
    		Console.WriteLine("Gender:      {0}", (System.Char)gender);
    		Console.Write("Organ Donor? ");
    		if( strOrganDonor.Equals("1") )
    			Console.WriteLine("Yes");
    		else
    			Console.WriteLine("No");
    		Console.WriteLine();
    	}
    }
  2. Execute the application and test it
  3. Return to Notepad

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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		int number1, number2, maximum;
		String strNum1, strNum2;
	
		Console.Write("Enter first numbers: ");
		strNum1 = Console.ReadLine();
		Console.Write("Enter second numbers: ");
		strNum2 = Console.ReadLine();
		
		number1 = Integer.parseInt(strNum1);
		number2 = Integer.parseInt(strNum2);
	
		maximum = (number1 < number2) ? number2 : number1;
	
		Console.Write("\nThe maximum of ");
		Console.Write(number1);
		Console.Write(" and ");
		Console.Write(number2);
		Console.Write(" is ");
		Console.WriteLine(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
 

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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		char answer;
		String strAns;
	
		// Request the availability of a credit card from the user
		Console.Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
		strAns = Console.ReadLine();
		answer = Char.Parse(strAns);

		if( answer == 'y' ) // First Condition
		{
			Console.WriteLine("\nThis job involves a high level of self-control.");
			Console.WriteLine("We will get back to you.\n");
		}
		else if( answer == 'n' ) // Alternative
			Console.Write("\nYou are hired!\n");
		else
			Console.Write("\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:
     
    package MVA1;
    import System.*;
    
    public class Exercise
    {
    	public static void main(String[] args)
    	{
    		String firstName, lastName;
    		String strOrganDonor;
    		char gender;
    	
    		Console.WriteLine(" -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Application ---");
    		Console.Write("First Name: ");
    		firstName = Console.ReadLine();
    		Console.Write("Last Name:  ");
    		lastName = Console.ReadLine();
    		Console.Write("Gender(F=Female/M=Male): ");
    		gender = Char.Parse(Console.ReadLine());
    		Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    		strOrganDonor = Console.ReadLine();
    
    		Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Information ---");
    		Console.WriteLine("Full Name:   {0} {1}", firstName, lastName);
    		Console.Write("Gender:      ");
    		
    		if( gender == 'f' )
    			Console.WriteLine("Female");
    		else if( gender == 'F' )
    			Console.WriteLine("Female");
    		else if( gender == 'm' )
    			Console.WriteLine("Male");
    		else if( gender == 'M' )
    			Console.WriteLine("Male");
    		else
    			Console.WriteLine("Unknown");
    		
    		Console.Write("Organ Donor? ");
    		if( strOrganDonor.Equals("1") )
    			Console.WriteLine("Yes");
    		else if( strOrganDonor.Equals("0") )
    			Console.WriteLine("No");
    
    		Console.WriteLine();
    	}
    }
  2. Execute the application and test it. 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

The switch Statement

When defining an expression whose result would lead to a specific program execution, the 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 in a case statement 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 System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		int Number;
		String Nbr;
	
		Console.Write("Type a number between 1 and 4: ");
		Nbr = Console.ReadLine();
		Number = Integer.parseInt(Nbr);
	
		switch(Number)
		{
			case 1:
				Console.WriteLine("You typed 1.");
			case 2:
				Console.WriteLine("You typed 2.");
			case 3:
				Console.WriteLine("You typed 3.");
			case 4:
				Console.WriteLine("You typed 4.");
		}
	}
}

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

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

Therefore another version of the program above would be

package Exercise;
import System.*;

public class Exercise
{
	public static void main(String[] args)
	{
		int Number;
		String Nbr;
	
		Console.Write("Type a number between 1 and 4: ");
		Nbr = Console.ReadLine();
		Number = Integer.parseInt(Nbr);
	
		switch(Number)
		{
			case 1:
				Console.WriteLine("You typed 1.");
			case 2:
				Console.WriteLine("You typed 2.");
			case 3:
				Console.WriteLine("You typed 3.");
			case 4:
				Console.WriteLine("You typed 4.");
			default:
				Console.Write(Number);
				Console.WriteLine(" is out of the requested range.");
		}
	}
}

Here is an example of running the program:

Type a number between 1 and 3: 8
8 is out of the requested range.

The switch statement can be used to combine cases executes as one. To do this, you can type two or more cases together.

 

Practical LearningPractical Learning: Using a switch Statement

  1. Change the file as follows:
     
    package MVA1;
    import System.*;
    
    public class Exercise
    {
    	public static void main(String[] args)
    	{
    		String firstName, lastName;
    		String strOrganDonor;
    		char gender;
    		char DLClass;
    	
    		Console.WriteLine(" -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Application ---");
    		Console.Write("First Name: ");
    		firstName = Console.ReadLine();
    		Console.Write("Last Name:  ");
    		lastName = Console.ReadLine();
    		Console.Write("Gender(F=Female/M=Male): ");
    		gender = Char.Parse(Console.ReadLine());
    		Console.WriteLine(" - Driver's License Class -");
    		Console.WriteLine("A - All Non-commercial vehicles except motorcycles");
    		Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.");
    		Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.");
    		Console.WriteLine("K - Mopeds");
    		Console.WriteLine("M - Motorcycles");
    		Console.Write("Your Choice: ");
    		DLClass = Char.Parse(Console.ReadLine());
    		Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ");
    		strOrganDonor = Console.ReadLine();
    
    		Console.WriteLine("\n -=- Motor Vehicle Administration -=-");
    		Console.WriteLine(" --- Driver's License Information ---");
    		Console.WriteLine("Full Name:   {0} {1}", firstName, lastName);
    		Console.Write("Gender:      ");
    		
    		if( gender == 'f' )
    			Console.WriteLine("Female");
    		else if( gender == 'F' )
    			Console.WriteLine("Female");
    		else if( gender == 'm' )
    			Console.WriteLine("Male");
    		else if( gender == 'M' )
    			Console.WriteLine("Male");
    		else
    			Console.WriteLine("Unknown");
    		
    		switch(DLClass)
    		{
    			case 'a':
    			case 'A':
    				Console.WriteLine("Class:       A");
    				break;
    			case 'b':
    			case 'B':
    				Console.WriteLine("Class:       B");
    				break;
    			case 'c':
    			case 'C':
    				Console.WriteLine("Class:       C");
    				break;
    			case 'k':
    			case 'K':
    				Console.WriteLine("Class:       K");
    				break;
    			case 'm':
    			case 'M':
    				Console.WriteLine("Class:       M");
    				break;
    			default:
    				Console.WriteLine("Class:       Unknown");
    				break;
    		}
    
    		Console.Write("Organ Donor? ");
    		if( strOrganDonor.Equals("1") )
    			Console.WriteLine("Yes");
    		else if( strOrganDonor.Equals("0") )
    			Console.WriteLine("No");
    
    		Console.WriteLine();
    	}
    }
  2. Execute the application and test it. 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-2010 FunctionX. Inc. Next