[英]How to add Exit or Retry in C# Coding (Visual Studio)
我目前是一名学生,刚刚学习C#
。 我正在尝试实现一个代码,以便您可以随时键入 exit 或 restart 。 我可以弄清楚如何 go 关于它或如何接近它。 再次,我对编码是全新的,并且在任何帮助之前没有任何背景。 谢谢你。 我已经发布了一张关于我所拥有的图片。
您可以使用“哨兵控制的 C# while 循环”!
您可以通过访问了解更多信息:- https://kodify.net/csharp/loop/sentinel-loop/
或者您可以尝试创建一个包含 if 语句的方法,该语句检查用户是否键入例如“exit”,然后您必须在每次用户可以键入时输入该方法名称,并且它会一直滚动,这很好,希望对你有帮助!
表示赞许,满意,胜利 !
根据您的描述,我为猜数字游戏制作了一个代码示例。
我用return退出游戏,用break重试游戏。
代码:
static void Main(string[] args)
{
int attempts = 0;
int answer = 45;
int guess = 12;
bool t = false;
while(attempts<5)
{
while (true)
{
Console.WriteLine("Guess a number between 0~100");
t = int.TryParse(Console.ReadLine(), out guess);
if (t == false)
{
Console.WriteLine("Your input is not a number, please input again, you have {0} changes",4-attempts);
break;
}
else
{
if(guess>100||guess<0)
{
Console.WriteLine("Your input number is not in the range, please input again, you have {0} changes", 4 - attempts);
break;
}
else
{
if(answer==guess)
{
Console.WriteLine("You guessed right");
Console.WriteLine("Game over");
Console.ReadLine();
return;
}
else
{
Console.WriteLine("You gueesed wrong, please input again, you have {0} changes", 4 - attempts);
break;
}
}
}
}
if (attempts == 4)
{
Console.WriteLine("You have no chances");
Console.WriteLine("Game over");
Console.ReadLine();
return;
}
attempts = attempts + 1;
}
}
测试结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.