Conditional Statements |
|
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.
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;
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:
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: 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 Learning: Using if |
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(); } } |
-=- 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 |
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;
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 Learning: Using if...else |
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(); } } |
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:
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 Learning: Using if...else if |
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(); } } |
-=- 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 |
Practical Learning: Using a switch Statement |
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(); } } |
-=- 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 |
|
||
Previous | Copyright © 2005-2010 FunctionX. Inc. | Next |
|