学习循环语句之前,先学习跳转语句
continue语句:跳出当前循环,开始一次新的循环,并没有结束循环
break语句:立刻结束循环
while循环语句
while循环语句可以一次都不执行循环体
举例:制作一个小游戏,输入两个和为100的数,积一分,否则游戏结束
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace StatementsExample3
{
internal class Program
{
static void Main(string[] args)
{
int score = 0;
bool canContinue = true;
while (canContinue)
{
Console.WriteLine("please input first numble.");
string str1= Console.ReadLine();
int x=int.Parse(str1);
Console.WriteLine("please input first numble.");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
int sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Corret!{0}+{1}={2}",x,y,sum);
}
else
{
Console.WriteLine("Error!{0}+{1}={2}",x,y,sum);
canContinue = false;
}
}
Console.WriteLine("Your score is {0}",score);
Console.ReadLine();
}
}
}
do 语句
无论如何都会执行一次循环体
仔细分析上面的代码,无论如何都会执行一次循环体,可以将代码修改如下:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace StatementsExample3
{
internal class Program
{
static void Main(string[] args)
{
int score = 0;
int sum;
do
{
Console.WriteLine("please input first numble.");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("please input first numble.");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Corret!{0}+{1}={2}", x, y, sum);
}
else
{
Console.WriteLine("Error!{0}+{1}={2}", x, y, sum);
}
} while (sum==100);
Console.WriteLine("Your score is {0}",score);
Console.ReadLine();
}
}
}
注意:
代码中可能出现错误,输入的数值可能会出现错误,比如输入的不是数字,或者超出了范围,需要使用try语句以及跳转语句。
以及当想主动结束游戏时,输入end结束,需要break语句
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace StatementsExample3
{
internal class Program
{
static void Main(string[] args)
{
int score = 0;
int sum=0;
do
{
Console.WriteLine("Please input first numble.");
string str1 = Console.ReadLine();
if(str1.ToLower()== "end")
{
break;
}
int x = 0;
try
{
x=int.Parse(str1);//该语句可能会出现错误,比如输入的不是数字,或者超出范围
}
catch
{
//当出现错误时,执行以下语句
Console.WriteLine("First number have problem!Restart.");
continue;//跳出当前循环,并执行一次新的循环
}
Console.WriteLine("Please input first numble.");
string str2 = Console.ReadLine();
if (str1.ToLower() == "end")
{
break;
}
int y = 0;
try
{
y = int.Parse(str2);
}
catch
{
Console.WriteLine("Second number have problem!Restart.");
continue;
}
sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Corret!{0}+{1}={2}", x, y, sum);
}
else
{
Console.WriteLine("Error!{0}+{1}={2}", x, y, sum);
}
} while (sum==100);
Console.WriteLine("Your score is {0}",score);
Console.ReadLine();
}
}
}