【C#语言入门】13. 表达式、语句详解(3)
四、语句详解
- statement:
- labeled-statement 标签语句
- declaration-statemnt 声明语句
- embedded-statedment 嵌入式语句
- embedded-statement
- block 块语句
- empty-statement 空语句
- expression-statement 表达式语句
- selection-statement 选择语句
- iteration-statement 迭代语句
- jump-statement 跳转语句
- try-statement try…catch…finally语句
- checked-statement check语句
- unchecked-statement unchecked语句
- lock-statement lock语句
- using-statement using语句
- yield-statement yield语句
十、迭代(循环)语句
迭代语句重复执行嵌入语句,有while、do、for、foreach四种语句
1. while语句
while语句按不同条件执行一个嵌入语句0次或多次。
int score = 0;
bool canContinue = true;
while (canContinue)
{
Console.WriteLine("Please input first number:");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("Please input second number:");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
int sum = x + y;
if(sum == 100)
{
score++;
Console.WriteLine(Correct!(0)+(1)=(2),x,y,sum);
}
else
{
Console.WriteLine(Error!(0)+(1)=(2),x,y,sum);
canContinue = false;
}
}
Console.WriteLine("Your scores are (0).",score);
2. do语句
do语句按不同条件执行一个嵌入语句一次或多次。
int score = 0;
int sum = 0;
do
{
Console.WriteLine("Please input first number:");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("Please input second number:");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
int sum = x + y;
if(sum == 100)
{
score++;
Console.WriteLine(Correct!(0)+(1)=(2),x,y,sum);
}
else
{
Console.WriteLine(Error!(0)+(1)=(2),x,y,sum);
}
}while(canContinue == 100);
Console.WriteLine("Your scores are (0).",score);
3. for语句
for语句计算一个初始化表达式序列,然后,当某个条件为真时,重复执行相关的嵌入语句并计算一个迭代表达式序列。(比较适用于计数的循环)
- for (for-initializer; for-condition; for-iterator ) embedded-statement
执行步骤:for-initializer(只执行一次)—》 for-condition(如果是true)—》embedded-statement—》for-iterator
for (int counter = 0; counter < 10;counter++)
{
Console.WriteLine("Hello,World!");
}
4. foreach语句
foreach语句用于枚举一个集合的元素,并对该集合中的每个元素执行一次相关的嵌入语句。(最佳应用场合就是对集合进行遍历)
int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
List<int> intList = new Lit<int>(){1, 2, 3, 4, 5, 6};
foreach(var current in intList)
{
Console.WriteLine(current);
}
十一、跳转语句
1. break语句
break语句将退出直接封闭它的switch、while、do、for 或者 foreach语句。
2. continue语句
continue语句将开始直接封闭它的while、do、for、foreach语句的一次新迭代。
int score = 0;
int sum = 0;
do
{
Console.WriteLine("Please input first number:");
string str1 = Console.ReadLine();
try
{
int x = int.Parse(str1);
}
catch
{
Console.WriteLine("First number has problem!Restart.");
continue;
}
Console.WriteLine("Please input second number:");
string str2 = Console.ReadLine();
try
{
int y = int.Parse(str2);
}
catch
{
Console.WriteLine("Second number has problem!Restart.");
continue;
}
int sum = x + y;
if(sum == 100)
{
score++;
Console.WriteLine(Correct!(0)+(1)=(2),x,y,sum);
}
else
{
Console.WriteLine(Error!(0)+(1)=(2),x,y,sum);
}
}while(canContinue == 100);
Console.WriteLine("Your scores are (0).",score);