c# - 如何在 C# Coding (Visual Studio) 中添加退出或重试
问题描述
我目前是一名学生,刚刚学习C#
。我正在尝试实现一个代码,以便您可以随时键入 exit 或 restart 。我可以弄清楚如何去做或如何接近它。再次,我对编码是全新的,并且在任何帮助之前没有任何背景。谢谢你。我已经发布了一张关于我所拥有的图片。
解决方案
根据您的描述,我为猜数字游戏制作了一个代码示例。
我用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;
}
}
测试结果:
推荐阅读
- python - 检测 Pandas Dataframe 中的浮点值
- angularjs - 通过将文本作为键传递来使用角度翻译
- arrays - 如何在 Julia 中不同类型的多维数组之间进行转换
- matlab - 非线性回归为每次运行产生不同的结果
- javascript - 在开关上无法访问的变量
- reactjs - 使用 React+Redux 从数据库中设置 initialState 值
- python - 如何使用 pptx-python 设置幻灯片的大小?
- javascript - 删除处理程序不在范围内的事件侦听器
- javascript - 每当远程主机关闭套接字连接时,Node.js 应用程序就会崩溃
- git - 如何在 Mac Mojave 上设置 kdiff3?