Topics on Creating and Using Conditional Statements
Topics on Creating and Using Conditional Statements
The Boolean Data Type
Introduction
When initializing a Boolean variable or setting its value, we saw that you can assign a true or false value to it. A Boolean variable can also be initialized with a Boolean expression. Here is an example:
public class Exercise
{
private void Create()
{
bool employeeIsFullTime = position == "Manager";
}
}
To make your code easy to read, you should include the logical expression in parentheses. This can be done as follows:
public class Exercise
{
string GetEmployeePosition()
{
return "Associate Director";
}
public void Create()
{
string position = "";
bool employeeIsFullTime = (position == "Manager");
}
}
Reading a Key from the Console
When it finishes reading its key, the Console.ReadKey() method stops and lets you decide what to do. If you want it to display the result, the Console class provides another version of the ReadKey() method. Its syntax is:
public static ConsoleKeyInfo ReadKey(bool intercept);
The Boolean argument specifies whether you want the method to display the value.
Methods and Conditional Statements
Returning From a Method
So far, when defining a void method, we did not return a value. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}
In reality a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
return;
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}
In this case, the return; operation doesn't serve any true purpose. In the next section, we will see how it can be made useful when associated with a conditional statement.
Practical Learning: Introducing Methods and Conditions
public enum AccountType { Checking, Saving, Other } public class Customer { public string AccountNumber; public AccountType Type; public string FullName; public double Balance; public short PIN; public Customer(string acnt = "000-000000-000", AccountType category = AccountType.Other, string name = "John Doe") { AccountNumber = acnt; Type = category; FullName = name; PIN = 0; Balance = 0.00D; } }
using System; public class Management { private Customer CreateNewAccount() { int typeOfAccount = 0; Customer client = new Customer(); Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("-------------------------------------------"); Console.Write("Enter a number for the new account(000-000000-000): "); client.AccountNumber = Console.ReadLine(); Console.WriteLine("What type of account the customer wants to open"); Console.WriteLine("1 - Checking Account"); Console.WriteLine("2 - Savings Account"); Console.Write("Enter account type: "); typeOfAccount = int.Parse(Console.ReadLine()); if (typeOfAccount == 1) client.Type = AccountType.Checking; else if (typeOfAccount == 2) client.Type = AccountType.Saving; else client.Type = AccountType.Other; Console.Write("Enter customer name: "); client.FullName = Console.ReadLine(); Console.Write("Ask the customer to enter a PIN: "); client.PIN = short.Parse(Console.ReadLine()); return client; } public double GetMoney() { double amount = 0; Console.Write("Amount: "); amount = double.Parse(Console.ReadLine()); return amount; } private void ShowAccountInformation(Customer cust) { Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("Customer Account Information"); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Account #: {0}", cust.AccountNumber); Console.WriteLine("Account Type: {0}", cust.Type); Console.WriteLine("Full Name: {0}", cust.FullName); Console.WriteLine("PIN #: {0}", cust.PIN); Console.WriteLine("Balance: {0:F}", cust.Balance); Console.WriteLine("==========================================="); return; } public static int Main() { double amount = 0; int nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = int.Parse(Console.ReadLine()); Console.Clear(); switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: Console.Write("Enter Deposit "); amount = registration.GetMoney(); accountHolder.Balance = accountHolder.Balance + amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: Console.Write("Enter Withdrawal "); amount = registration.GetMoney(); if (amount > accountHolder.Balance) { Console.WriteLine("You are not allowed to withdraw more money than your account has."); Console.ReadKey(); } else accountHolder.Balance = accountHolder.Balance - amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine("Operation not available: You have only one account with us"); break; } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); return 0; } }
Conditional Return
Some methods are meant to return a value that depends on their operations. The fact that a method indicates the type of value it would return may not be clear at the time the method is closed but a method defined other than void must always return a value. You can write a conditional statement, such as an if statement, inside of a function and return a value from that condition. Here is an example:
using System; public class Program { enum HouseType { Unknown, SingleFamily, Townhouse, Condominium }; public static int Main() { var type = GetHouseType(); switch (type) { case HouseType.SingleFamily: Console.WriteLine("\nType of Home: Single Family"); break; case HouseType.Townhouse: Console.WriteLine("\nType of Home: Townhouse"); break; case HouseType.Condominium: Console.WriteLine("\nType of Home: Condominium"); break; case HouseType.Unknown: Console.WriteLine("\nType of Home. Unknown"); break; } return 0; } private static HouseType GetHouseType() { var type = 0; Console.WriteLine("What Type of House Would you Like to Purchase?"); Console.WriteLine("1 - Single Family"); Console.WriteLine("2 - Townhouse"); Console.WriteLine("3 - Condominium"); Console.Write("Your Choice? "); type = int.Parse(Console.ReadLine()); if (type == 1) return HouseType.SingleFamily; else if (type == 2) return HouseType.Townhouse; else if (type == 3) return HouseType.Condominium; } }
This GetHouseType() method indicates when one of three values is returned. In reality, this method could get a value other than the three that are considered. If the user enters such a value, the current version of the method would not know what to do. For this reason, the program will not compile. In Microsoft Visual C#, you would receive the following error:
'Program.GetHouseType()': not all code paths return a value
To solve this problem, you must provide a statement that would include any value other than those considered. You can do this by writing a final return that has its own value. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
else
return HouseType.Unknown;
}
}
Practical Learning: Conditionally Returning a Value
using System; public class Management { private AccountType SpecifyAccountType() { int type = 0; Console.WriteLine("What type of account the customer wants to open"); Console.WriteLine("1 - Checking Account"); Console.WriteLine("2 - Savings Account"); Console.Write("Enter account type: "); type = int.Parse(Console.ReadLine()); if (type == 1) return AccountType.Checking; else if (type == 2) return AccountType.Saving; else return AccountType.Other; } private Customer CreateNewAccount() { Customer client = new Customer(); . . . No Change return client; } public double Deposit() { double amount = 0; Console.Write("Amount to deposit: "); amount = double.Parse(Console.ReadLine()); return amount; } public double Withdraw(Customer cust) { double amount = 0; Console.Write("Amount to withdraw: "); amount = double.Parse(Console.ReadLine()); if (amount > cust.Balance) { Console.WriteLine("You are not allowed to withdraw more money than your account has."); Console.ReadKey(); return 0.00D; } else return amount; } private void ShowAccountInformation(Customer cust) { . . . No Change } public static int Main() { double amount = 0; int nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.Deposit(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("0 - Close the application"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = int.Parse(Console.ReadLine()); Console.Clear(); switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: amount = registration.Deposit(); accountHolder.Balance += amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: amount = registration.Withdraw(accountHolder); accountHolder.Balance -= amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine("Operation not available: You have only one account with us"); break; default: return 0; } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); Console.ReadKey(); return 0; } }
Account #: | 257-484902-444 |
Account Type: | 1 |
Customer Name: | Josh Nay |
PIN: | 5008 |
Initial Deposit | 250 |
=========================================== ==-= National Bank =-====================== ------------------------------------------- New Account Number (000-000000-000): 257-484902-444 What type of account the customer wants to open 1 - Checking Account 2 - Savings Account Enter account type: 1 Enter customer name: Josh Nay Ask the customer to enter a PIN: 5008 Enter the customer's initial deposit Amount to deposit: 250
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 250.00 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 85.63 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 201.81 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
Amount to withdraw: 300 You are not allowed to withdraw more money than your account has.
Returning From a Method
So far, when defining a void method, we did not return a value. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}
In reality, a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
return;
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}
In this case, the return; operation doesn't serve any true purpose. Still, it can be useful when associated with a conditional statement.
Practical Learning: Introducing Methods and Conditions
public enum AccountType { Checking, Saving, Other } public class Customer { public string AccountNumber; public AccountType Type; public string FullName; public double Balance; public short PIN; public Customer(string acnt = "000-000000-000", AccountType category = AccountType.Other, string name = "John Doe") { AccountNumber = acnt; Type = category; FullName = name; PIN = 0; Balance = 0.00D; } }
using System; public class Management { private Customer CreateNewAccount() { byte typeOfAccount = 0; Customer client = new Customer(); Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("-------------------------------------------"); Console.Write("Enter a number for the new account(000-000000-000): "); client.AccountNumber = Console.ReadLine(); Console.WriteLine("What type of account the customer wants to open"); Console.WriteLine("1 - Checking Account"); Console.WriteLine("2 - Savings Account"); Console.Write("Enter account type: "); typeOfAccount = byte.Parse(Console.ReadLine()); if (typeOfAccount == 1) client.Type = AccountType.Checking; else if (typeOfAccount == 2) client.Type = AccountType.Saving; else client.Type = AccountType.Other; Console.Write("Enter customer name: "); client.FullName = Console.ReadLine(); Console.Write("Ask the customer to enter a PIN: "); client.PIN = short.Parse(Console.ReadLine()); return client; } public double GetMoney() { double amount = 0; Console.Write("Amount: "); amount = double.Parse(Console.ReadLine()); return amount; } private void ShowAccountInformation(Customer cust) { Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("Customer Account Information"); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Account #: {0}", cust.AccountNumber); Console.WriteLine("Account Type: {0}", cust.Type); Console.WriteLine("Full Name: {0}", cust.FullName); Console.WriteLine("PIN #: {0}", cust.PIN); Console.WriteLine("Balance: {0:F}", cust.Balance); Console.WriteLine("==========================================="); return; } public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = byte.Parse(Console.ReadLine()); Console.Clear(); switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: Console.Write("Enter Deposit "); amount = registration.GetMoney(); accountHolder.Balance = accountHolder.Balance + amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: Console.Write("Enter Withdrawal "); amount = registration.GetMoney(); if (amount > accountHolder.Balance) { Console.WriteLine("You are not allowed to withdraw more money than your account has."); Console.ReadKey(); } else accountHolder.Balance = accountHolder.Balance - amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine("Operation not available: You have only one account with us"); break; } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); Console.ReadKey(); return 0; } }
Conditional Return
Some methods are meant to return a value that is conditional of their processing. The fact that a method indicates the type of value it would return may not be clear at the time the method is closed but a method defined other than void must always return a value. You can write a conditional statement, such as an if condition, inside of a method and return a value from that condition. Here is an example:
using System; public class Program { enum HouseType { Unknown, SingleFamily, Townhouse, Condominium }; public static int Main() { var type = GetHouseType(); switch (type) { case HouseType.SingleFamily: Console.WriteLine("\nType of Home: Single Family"); break; case HouseType.Townhouse: Console.WriteLine("\nType of Home: Townhouse"); break; case HouseType.Condominium: Console.WriteLine("\nType of Home: Condominium"); break; case HouseType.Unknown: Console.WriteLine("\nType of Home. Unknown"); break; } return 0; } private static HouseType GetHouseType() { var type = 0; Console.WriteLine("What Type of House Would you Like to Purchase?"); Console.WriteLine("1 - Single Family"); Console.WriteLine("2 - Townhouse"); Console.WriteLine("3 - Condominium"); Console.Write("Your Choice? "); type = int.Parse(Console.ReadLine()); if (type == 1) return HouseType.SingleFamily; else if (type == 2) return HouseType.Townhouse; else if (type == 3) return HouseType.Condominium; } }
This GetHouseType() method indicates when one of three values is returned. In reality, this method could get a value other than the three that are considered. If the user enters such a value, the current version of the method would not know what to do. For this reason, the program will not compile. In Microsoft Visual C#, you would receive the following error:
'Program.GetHouseType()': not all code paths return a value
To solve this problem, you must provide a statement that would include any value other than those considered. You can do this by writing a final return that has its own value. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
else
return HouseType.Unknown;
}
}
Practical Learning: Conditionally Returning a Value
using System; public class Management { private AccountType SpecifyAccountType() { byte type = 0; Console.WriteLine("What type of account the customer wants to open"); Console.WriteLine("1 - Checking Account"); Console.WriteLine("2 - Savings Account"); Console.Write("Enter account type: "); type = byte.Parse(Console.ReadLine()); if (type == 1) return AccountType.Checking; else if (type == 2) return AccountType.Saving; else return AccountType.Other; } private Customer CreateNewAccount() { Customer client = new Customer(); . . . No Change return client; } public double Deposit() { double amount = 0; Console.Write("Amount to deposit: "); amount = double.Parse(Console.ReadLine()); return amount; } public double Withdraw(Customer cust) { double amount = 0; Console.Write("Amount to withdraw: "); amount = double.Parse(Console.ReadLine()); if (amount > cust.Balance) { Console.WriteLine("You are not allowed to withdraw more money than your account has."); Console.ReadKey(); return 0.00D; } else return amount; } private void ShowAccountInformation(Customer cust) { . . . No Change } public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.Deposit(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("0 - Close the application"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = byte.Parse(Console.ReadLine()); Console.Clear(); switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: amount = registration.Deposit(); accountHolder.Balance += amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: amount = registration.Withdraw(accountHolder); accountHolder.Balance -= amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine("Operation not available: You have only one account with us"); break; default: return 0; } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); Console.ReadKey(); return 0; } }
Account #: | 257-484902-444 |
Account Type: | 1 |
Customer Name: | Josh Nay |
PIN: | 5008 |
Initial Deposit | 250 |
=========================================== ==-= National Bank =-====================== ------------------------------------------- New Account Number (000-000000-000): 257-484902-444 What type of account the customer wants to open 1 - Checking Account 2 - Savings Account Enter account type: 1 Enter customer name: Josh Nay Ask the customer to enter a PIN: 5008 Enter the customer's initial deposit Amount to deposit: 250
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 250.00 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 85.63 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 257-484902-444 Account Type: Checking Full Name: Josh Nay PIN #: 5008 Balance: 201.81 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
Amount to withdraw: 300 You are not allowed to withdraw more money than your account has.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|