当前位置:网站首页>[C # process control] - if/switch selection structure in C #
[C # process control] - if/switch selection structure in C #
2022-07-20 22:14:00 【Burning and blowing】
##################################################
Catalog
switch And if Choose structural comprehensive test
##################################################
if Selection structure
——————————
Code style.
C# Of if The grammar of structure and Java It's exactly the same in
however So let's talk about that C# Standard code style !
In order to make if Structure is clearer We put each if/else Contained statements All enclosed in curly braces
A matching pair of if/else Align left
The inner layer of the if The structure should be indented
Braces are compared according to the standard writing :
C# Curly braces
{
and
}
One line each
Java Left brace
{
Immediately follow the conditions
Right brace
}
Start a new line
These programming habits Mainly to improve the readability of the program
——————————
single if structure
The grammar is as follows :
if ( Conditional expression )
{
// Code block
}
——————————
if-else structure
The grammar is as follows :
if ( Conditional expression )
{
// Code block
}
else
{
// Code block
}
——————————
multiple if structure
grammar :
if ( Conditional expression )
{
// Code block
}
else if ( Conditional expression )
{
// Code block
}
else if ( Conditional expression )
{
// Code block
}
else
{
// Code block
}
——————————
nesting if structure
Remember nesting if Do you ?
Only meet the outer layer if Conditions To judge the inner layer if Conditions
Another thing to note else With the recent lack else The block if Match
Grammar format :
if ( Conditional expression )
{
if ( Conditional expression )
{
// Code block
}
else
{
// Code block
}
}
else
{
// Code block
}
——————————
if Select structural test
%%%%%
SBS Withdrawal business
stay SBS On the basis of account opening business add to Withdrawal function
Requirements are as follows :
Judge whether the entered account number is correct
correct Withdraw money Otherwise output Account does not exist
Judge whether the password is correct
Consistent continue Otherwise output The password is wrong
If the withdrawal amount is greater than 0 And the withdrawal amount shall not be greater than the balance Then update the balance And prompt Successful withdrawals
Otherwise output Withdrawal failed
VScode code:
namespace _6.SBS_ Withdrawal business
{
/* Ideas
*
* stay Bank Definition in class Withdrawal method module Used to receive user input information And call User Class Withdrawal method implementation module
*
* stay User Definition in class Withdrawal method implementation module
* Use nesting if To judge
* The outer layer is used to judge whether the withdrawal amount is greater than 0
* The inner layer is used to judge whether the withdrawal amount is greater than balance
*
* stay Main() Instantiation in Bank Class object call Account opening module Account opening built-in call withdrawal module
*/
/// <summary>
/// Banking
/// </summary>
public class Bank
{
/* Field is temporarily missing
* ... ...
*/
/* Be sure to declare global objects Because there is more than one method to use ! */
User usr = new User();
/// <summary>
/// Account opening method
/// </summary>
public void CreateAccount()
{
/* initialization */
string account = "163729837463"; // Randomly assigned account
/* receive data */
usr._account = account; // Get the account number
Console.Write(" Please enter a user name <<< ");
usr._name = Console.ReadLine(); // Get the user name
Console.Write(" Please enter the user password <<< ");
usr._pass = Console.ReadLine(); // Get the user password
Console.Write(" Please enter user ID number. <<< ");
usr._identityNum = Console.ReadLine(); // Get the user's ID number
Console.Write(" Please enter user deposit amount <<< ");
usr._balance = double.Parse(Console.ReadLine()); // Get the user's deposit amount
/* Output information */
Console.WriteLine("\n\t Account {0}\n\t user name {1}\n\t Amount of deposit {2}\n\t Create success !",
usr._account, usr._name, usr._balance);
/* Call the withdrawal business */
WithDraw();
}
/// <summary>
/// Method of withdrawal
/// </summary>
public void WithDraw()
{
/* Get ready */
string account; // account number
string pwd; // password
double money; // Withdrawal amount
double result; // Return balance
/* Receive account verification */
Console.WriteLine();
Console.Write(" Please enter your account number <<< ");
account = Console.ReadLine();
if (account.Length == 0)
{ /* Lazy here Only judge the account length _(:з」∠)_ ! */
Console.WriteLine("..> The account number entered is incorrect ..\n");
return; // Do you remember? ? conversant return ! If the length is not correct, return to the calling method
}
/* Receive password verification */
Console.Write(" Please enter the account password <<< ");
pwd = Console.ReadLine();
if (usr._pass != pwd)
{ /* Not lazy this time Match the newly obtained password with User Class Password field Compare */
Console.WriteLine("..> The password is wrong !\n");
return;
}
/* Withdrawal operations */
Console.Write(" Please enter the withdrawal amount <<< ");
money = double.Parse(Console.ReadLine()); // call double.Parse() Convert the resulting string to double Reassign to money
result = usr.MinusMoney(money); // call User Class Withdrawal implementation module Get the balance after withdrawal
/* Results output */
if (result == -1)
{ /* If it turns out -1 It means that the withdrawal failed .. */
Console.WriteLine("..> Withdrawal failed !\n");
}
else
{
Console.WriteLine("..> Successful withdrawals ! Current balance : {0}\n", result);
}
/* Program end */
Console.ReadLine();
}
}
/// <summary>
/// Account type
/// </summary>
public class User
{
public string _name; // user name
public string _account; // account number
public string _pass; // User password
public string _identityNum; // ID number
public double _balance; // Balance of deposit
/// <summary>
/// Withdrawal method
/// </summary>
/// <param name="money"> The amount to be obtained </param>
/// <returns> Return balance if -1 Then the input is incorrect </returns>
public double MinusMoney(double money)
{
if (money > 0)
{ /* Judge whether the withdrawal amount is greater than 0 */
if (money <= _balance)
{ /* Judge whether the withdrawal amount is greater than the balance */
_balance -= money; // -= Familiar with? ? amount to _balance = _balance - money
return _balance;
}
else
{
return -1;
}
}
else
{
return -1;
}
}
}
/// <summary>
/// The main class
/// </summary>
class Program
{
/// <summary>
/// Main Method
/// </summary>
static void Main(string[] args)
{
/* The account opening module calls the withdrawal module Call to open an account ! */
Bank ba = new Bank();
ba.CreateAccount();
ba.CreateAccount();
ba.CreateAccount();
ba.CreateAccount();
ba.CreateAccount();
}
}
}
VSCode demo:
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 666999
Account 163729837463
user name first
Amount of deposit 666999
Create success !
Please enter your account number <<<
..> The account number entered is incorrect ..
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 666999
Account 163729837463
user name first
Amount of deposit 666999
Create success !
Please enter your account number <<< 163729837463
Please enter the account password <<< 123
..> The password is wrong !
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 666999
Account 163729837463
user name first
Amount of deposit 666999
Create success !
Please enter your account number <<< 163729837463
Please enter the account password <<< 123456
Please enter the withdrawal amount <<< -521
..> Withdrawal failed !
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 666999
Account 163729837463
user name first
Amount of deposit 666999
Create success !
Please enter your account number <<< 163729837463
Please enter the account password <<< 123456
Please enter the withdrawal amount <<< 999666
..> Withdrawal failed !
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 666999
Account 163729837463
user name first
Amount of deposit 666999
Create success !
Please enter your account number <<< first
Please enter the account password <<< 123456
Please enter the withdrawal amount <<< 999
..> Successful withdrawals ! Current balance : 666000
##################################################
switch Selection structure
——————————
C# switch And Java Different
C# Of switch Structure and Java Different
Java allow case There is no break In this way, the program will continue to the next case Or finished switch
Keep up with the switch The value or variable of the following expression can be integer or characterC# Ask for each case Block and default Every block must have break sentence !
Except for two case There are no other sentences between blocks So the first one case A block may not contain break
C# Of switch More flexible The expression of judgment is in addition to variables It can also be a string type
And the early Java It cannot be a string type
%%%%%
Java's switch
Grammar format :
switch ( int/char expression ) {
case Constant expression _1:
// Code block
break; /* There can be no break sentence */
case Constant expression _2:
// Code block
break; /* There can be no break sentence */
case Constant expression _N:
// Code block
break; /* There can be no break sentence */
default:
// Code block
}
%%%%%
C# switch Standard grammar
Grammar format :
switch (int/char/string expression )
{
case Constant expression _1:
// Code block
break; /* There must be */
case Constant expression _2:
// Code block
break; /* There must be */
case Constant expression _N:
// Code block
break; /* There must be */
default:
// Code block
break; /* There must be */
}
If you want to omit break sentence Two case There are no other sentences
The first one case Blocks can be omitted break sentence
If so Regardless of switch Whether the expression satisfies the former or the latter case expression
Will execute the previous case block Because of the previous case The block is empty
Then the program executes the following case block Until I met break The statement so far
In the following example case_2、case_3 There is no statement between
therefore case_2 Omission break sentence
here If meet case_2/case_3 Will execute case_2
C# switch nothing break Grammar format :
switch (int/char/string expression )
{
case Constant expression _1:
// Code block
break;
case Constant expression _2:
/* There is no content Omission break sentence */
case Constant expression _3:
// Code block
break;
case Constant expression _4:
// Code block
break;
case Constant expression _N:
// Code block
break;
default:
// Code block
break;
}
The last thing to say is this switch In structure case The placement of clauses is out of order
That is to say You can put default Clause at the front What needs to be noticed at this time is :
Any two case Statements cannot have the same value
by the way No matter what form it is switch
case The value in the clause must be a constant expression Variables are not allowed
——————————
switch Small exercise
%%%%%
Full name of Bank
There is a comparison table of the abbreviations and full names of the three banks Please output the full name of the corresponding bank according to the entered abbreviation
The abbreviation is compared with the full name :
ICBC ICBC
CBC China Construction Bank
ABC the Agricultural Bank of China
Ideas :
Such problems are equivalent judgments
Easy to use switch Structure implementation
VSCode code:
using System;
namespace _7. Small exercise _ Full name of Bank
{
/// <summary>
/// Bank address
/// </summary>
class FullBankName
{
/// <summary>
/// Output bank full name method
/// </summary>
public void BankNameOutPut()
{ /* Output the full name by entering the abbreviation */
Console.Write(" Please enter the bank abbreviation <<< ");
string bank = Console.ReadLine().ToUpper(); // Remember Java How to convert capital letters ?
Console.WriteLine("\n##################################################");
switch (bank)
{
case "ICBC":
Console.WriteLine(">>> ICBC ");
break;
case "CBC":
Console.WriteLine(">>> China Construction Bank ");
break;
case "ABC":
Console.WriteLine(">>> the Agricultural Bank of China ");
break;
default:
Console.WriteLine("..> Input error !");
break;
}
Console.ReadLine();
}
}
/// <summary>
/// The main class
/// </summary>
class Program
{
/// <summary>
/// Main method
/// </summary>
static void Main(string[] args)
{
FullBankName bankName = new FullBankName();
bankName.BankNameOutPut();
bankName.BankNameOutPut();
bankName.BankNameOutPut();
bankName.BankNameOutPut();
}
}
}
VSCode demo:
Please enter the bank abbreviation <<< ICBC
##################################################
>>> ICBC
Please enter the bank abbreviation <<< CBC
##################################################
>>> China Construction Bank
Please enter the bank abbreviation <<< ABC
##################################################
>>> the Agricultural Bank of China
Please enter the bank abbreviation <<< 5211314
##################################################
..> Input error !
——————————
Get rid of break test
%%%%%
Cabbage price on Monday
If you will just switch Remove the structure break It's a mistake
So when can I not write break Well ?
This is in We have several case Do the same thing when conditions are met when
You can group them In the last case Write processing code !
This can greatly reduce the amount of code ! Improve program efficiency
demand :
according to Monday ~ Sunday Output cabbage price
1、2、3 Chinese cabbage 1000 element
4、5 Chinese cabbage 2000 element
6、7 Chinese cabbage 3000 element
Other values display error messages
Ideas :
Output the same information according to You can put break Put it last case in
VSCode vode:
namespace _8. Small exercise _ Cabbage price on Monday
{
/// <summary>
/// Week class
/// </summary>
class Week
{
/// <summary>
/// Output week method
/// </summary>
public void PrintWeek()
{ /* Output weekly price */
Console.Write(" Please enter the day of the week <<< ");
string week = Console.ReadLine();
Console.WriteLine("\n##################################################");
switch (week) // Note that the value of the expression here is of string type
{
case " One ":
case " Two ":
case " 3、 ... and ":
Console.WriteLine(" Cabbage price >>> 1000 ¥");
break;
case " Four ":
case " 5、 ... and ":
Console.WriteLine(" Cabbage price >>> 2000 ¥");
break;
case " 6、 ... and ":
case " Japan ":
Console.WriteLine(" Cabbage price >>> 3000 ¥");
break;
default:
Console.WriteLine("..> Input error !");
break;
}
Console.ReadLine();
}
}
/// <summary>
/// The main class
/// </summary>
class Program
{
/// <summary>
/// Main method
/// </summary>
static void Main(string[] args)
{
Week we = new Week();
we.PrintWeek();
we.PrintWeek();
we.PrintWeek();
we.PrintWeek();
}
}
}
VSCode demo:
Please enter the day of the week <<< Two
##################################################
Cabbage price >>> 1000 ¥
Please enter the day of the week <<< Four
##################################################
Cabbage price >>> 2000 ¥
Please enter the day of the week <<< Japan
##################################################
Cabbage price >>> 3000 ¥
Please enter the day of the week <<< 8、 ... and
##################################################
..> Input error !
##################################################
switch And if Choose structural comprehensive test
——————————
Project advancement
%%%%%
SBS system menu
stay SBS Project withdrawal function On the basis of add to system menu function
Requirements are as follows :
After the account is opened successfully The output window displays a menu
Then implement Menu sub module
Finally, according to this menu call Withdrawal sub module
VSCode code:
namespace _9.SBS_ Withdrawal business
{
/* Ideas
*
* What should be used in the menu ? you 're right switch son !
* We use switch Structure select to execute a specific statement
*
* stay Bank Class to create methods to implement menu functions Output menu options
* Use switch Judge and process the value entered by the user
* stay Main() Call in
*/
/// <summary>
/// Banking
/// </summary>
public class Bank
{
/* Field is temporarily missing
* ... ...
*/
/* Be sure to declare global objects Because there is more than one method to use ! */
User usr = new User();
/// <summary>
/// Menu module
/// </summary>
public void ShowCustomMenu()
{
Console.WriteLine();
Console.WriteLine("########## Welcome to the automated banking service ##########");
Console.WriteLine("1. deposit 2. Withdraw money 3. Transfer accounts 4. Inquire about 5. sign out ");
Console.WriteLine("##################################################");
Console.Write(" Please select <<< ");
string option = Console.ReadLine();
switch (option)
{
case "1":
// Deposit module
break;
case "2":
// Withdrawal module
WithDraw(); // Call the withdrawal method
break;
case "3":
// Transfer module
break;
case "4":
// Query module
break;
case "5":
// Exit the system
break;
default:
// Error message
Console.WriteLine("..> Invalid value entered !");
break;
}
// Program end
Console.ReadLine();
}
/// <summary>
/// Account opening method
/// </summary>
public void CreateAccount()
{
/* initialization */
string account = "163729837463"; // Randomly assigned account
/* receive data */
usr._account = account; // Get the account number
Console.Write(" Please enter a user name <<< ");
usr._name = Console.ReadLine(); // Get the user name
Console.Write(" Please enter the user password <<< ");
usr._pass = Console.ReadLine(); // Get the user password
Console.Write(" Please enter user ID number. <<< ");
usr._identityNum = Console.ReadLine(); // Get the user's ID number
Console.Write(" Please enter user deposit amount <<< ");
usr._balance = double.Parse(Console.ReadLine()); // Get the user's deposit amount
/* Output information */
Console.WriteLine("\n\t Account {0}\n\t user name {1}\n\t Amount of deposit {2}\n\t Create success !",
usr._account, usr._name, usr._balance);
/* Call the withdrawal business */
WithDraw();
}
/// <summary>
/// Method of withdrawal
/// </summary>
public void WithDraw()
{
/* Get ready */
string account; // account number
string pwd; // password
double money; // Withdrawal amount
double result; // Return balance
/* Receive account verification */
Console.WriteLine();
Console.Write(" Please enter your account number <<< ");
account = Console.ReadLine();
if (account.Length == 0)
{ /* Lazy here Only judge the account length _(:з」∠)_ ! */
Console.WriteLine("..> The account number entered is incorrect ..\n");
return; // Do you remember? ? conversant return ! If the length is not correct, return to the calling method
}
/* Receive password verification */
Console.Write(" Please enter the account password <<< ");
pwd = Console.ReadLine();
if (usr._pass != pwd)
{ /* Not lazy this time Match the newly obtained password with User Class Password field Compare */
Console.WriteLine("..> The password is wrong !\n");
return;
}
/* Withdrawal operations */
Console.Write(" Please enter the withdrawal amount <<< ");
money = double.Parse(Console.ReadLine()); // call double.Parse() Convert the resulting string to double Reassign to money
result = usr.MinusMoney(money); // call User Class Withdrawal implementation module Get the balance after withdrawal
/* Results output */
if (result == -1)
{ /* If it turns out -1 It means that the withdrawal failed .. */
Console.WriteLine("..> Withdrawal failed !\n");
}
else
{
Console.WriteLine("..> Successful withdrawals ! Current balance : {0}\n", result);
}
/* Program end */
Console.ReadLine();
}
}
/// <summary>
/// Account type
/// </summary>
public class User
{
public string _name; // user name
public string _account; // account number
public string _pass; // User password
public string _identityNum; // ID number
public double _balance; // Balance of deposit
/// <summary>
/// Withdrawal method
/// </summary>
/// <param name="money"> The amount to be obtained </param>
/// <returns> Return balance if -1 Then the input is incorrect </returns>
public double MinusMoney(double money)
{
if (money > 0)
{ /* Judge whether the withdrawal amount is greater than 0 */
if (money <= _balance)
{ /* Judge whether the withdrawal amount is greater than the balance */
_balance -= money; // -= Familiar with? ? amount to _balance = _balance - money
return _balance;
}
else
{
return -1;
}
}
else
{
return -1;
}
}
}
/// <summary>
/// The main class
/// </summary>
class Program
{
/// <summary>
/// Main Method
/// </summary>
static void Main(string[] args)
{
Bank ba = new Bank();
ba.CreateAccount(); // After the account is opened successfully
ba.ShowCustomMenu(); // Display system window And then choose Withdraw money Function can be !
}
}
}
For the time being, there is only the function of withdrawal module and exit module ……
VSCode demo:
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 5211314
Account 163729837463
user name first
Amount of deposit 5211314
Create success !
Please enter your account number <<< 163729837463
Please enter the account password <<< 123456
Please enter the withdrawal amount <<< 1314
..> Successful withdrawals ! Current balance : 5210000
########## Welcome to the automated banking service ##########
1. deposit 2. Withdraw money 3. Transfer accounts 4. Inquire about 5. sign out
##################################################
Please select <<< 2
Please enter your account number <<< 163729837463
Please enter the account password <<< 123456
Please enter the withdrawal amount <<< 21
..> Successful withdrawals ! Current balance : 5209979
The exit function is also OK Of :
Please enter a user name <<< first
Please enter the user password <<< 123456
Please enter user ID number. <<< 111111111111111111
Please enter user deposit amount <<< 521
Account 163729837463
user name first
Amount of deposit 521
Create success !
Please enter your account number <<< 163729837463
Please enter the account password <<< 123
..> The password is wrong !
########## Welcome to the automated banking service ##########
1. deposit 2. Withdraw money 3. Transfer accounts 4. Inquire about 5. sign out
##################################################
Please select <<< 5
You can see switch How important the structure is !
边栏推荐
- 谷歌请印度标注员给Reddit评论数据集打标签,错误率高达30%?
- Detailed interpretation: the use of reflection
- [C# 调试]-使用 VS 2012 IDE 环境调试 C# 代码
- (cvpr2020)Learning texture transformer network for image super-resolution论文阅读
- Hbuilderx Eslint配置
- 你真的了解图像吗?(机器视觉)
- 2022河南萌新联赛第(二)场:河南理工大学 L - HPU
- 云计算设计和规划安全控制措施
- 7 月最新编程排行榜:万年不变的前三,啥时候能是头?
- 聚合支付满足各行业接入多种支付
猜你喜欢
Dest0g3 520 orientation -web-fun_ upload
L'intervieweur m'a demandé pourquoi l'algorithme de collecte par génération GC de JVM était conçu de cette façon.
【面试必刷101】贪心算法、模拟、字符串
PyTorch随笔 - ConvMixer - Patches Are All You Need
Enter the real situation of maker education curriculum practice
数据仓库开发 SQL 使用技巧总结
史上最全的 IDEA Debug 调试技巧(超详细案例)
Simulate the implementation library function strcat-- append a copy of the source string to the target string (understand the memory overlap problem)
7 位艺术家因 NFT 而改变了自己的生活
串行加法器/减法器
随机推荐
DNS域名解析
北京邮电大学|RIS辅助室内多机器人通信系统的联合深度强化学习
Interpretation of openmmlab series framework (based on pytorch)
架构实战营第7模块作业
西北工业大学|使用交互式界面的多智能体模型协作
Problems solved in the company
面試官問我JVM的GC分代收集算法為什麼這麼設計
OTT大屏“新收视率体系”来了,广告主不再迷茫?
Simple examples of pointer arrays and array pointers
2022河南萌新联赛第(二)场:河南理工大学 L - HPU
(JS)不使用輔助空間找出數組中唯一成對的數
串行加法器/减法器
Open the physical space for the construction of maker education courses
大屏可视化适配文件
Using redis + Lua script to realize distributed flow restriction
Northwestern Polytechnical University | multi-agent model collaboration using interactive interfaces
Quickly install VMware tool for stm32mp157 development board
ES6-11 学习笔记
首个X光下的小样本检测基准和弱特征增强网络,北航、讯飞新研究入选ACM MM 2022
PyTorch笔记 - R-Drop、Conv2d、3x3+1x1+identity算子融合