[英]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.