當談到 C# 時,我是一個完全的新手,我相信這有一個非常簡單的答案:
我撰寫了一段超級簡單的代碼,使用戶能夠彈出一個數字并接收該數字的平方。我還允許用戶決定是否要玩,是、否或“其他”會觸發不同的結果。
“是”輸入作業正常,程式按預期作業。但是,“否”或“其他”回應似乎要求用戶在正確觸發結果之前再次輸入回應。
我不明白為什么它會連續兩次尋找回復,所以如果你能提供任何幫助,我會非常感激。
這是我正在使用的代碼:
namespace Playground { internal class Program { static void Main(string[] args) { Console.WriteLine("如果你輸入一個數字,我會報告這個數字的平方。你想玩嗎?輸入是或否");
int x = 100;
while (x == 100)
{
if (Console.ReadLine() == "Yes")
{
Console.WriteLine("Great! Enter a number");
int initial = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(initial * initial);
Console.WriteLine("Would you like to try again?");
}
else if(Console.ReadLine() == "No")
{
Console.WriteLine("Ok, goodbye! Press any key to Exit");
Console.ReadLine();
Environment.Exit(0);
}
else
{
Console.WriteLine("Sorry, I didn't understand that. Please enter Yes or No");
}
}
}
}
}
uj5u.com熱心網友回復:
當遇到第一個if
條件時,運行函式Console.ReadLine()
,所以你必須寫下答案。這也將發生在else if (Console.ReadLine() == "No")
.
您要做的就是只保存一次用戶輸入,然后根據該答案決定要做什么。
代碼是:
int x = 100;
while (x == 100)
{
string answer = Console.ReadLine();
if (answer == "Yes")
{
Console.WriteLine("Great! Enter a number");
int initial = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(initial * initial);
Console.WriteLine("Would you like to try again?");
}
else if(answer == "No")
{
Console.WriteLine("Ok, goodbye! Press any key to Exit");
Console.ReadLine();
Environment.Exit(0);
}
else
{
Console.WriteLine("Sorry, I didn't understand that. Please enter Yes or No");
}
}
您還可以使用以下switch
陳述句:
int x = 100;
while (x == 100){
string answer = Console.ReadLine();
switch (answer){
case "Yes":
Console.WriteLine("Great! Enter a number");
int initial = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(initial * initial);
Console.WriteLine("Would you like to try again?");
break;
case "No":
Console.WriteLine("Ok, goodbye! Press any key to Exit");
Console.ReadLine();
Environment.Exit(0);
break;
default:
Console.WriteLine("Sorry, I didn't understand that. Please enter Yes or No");
break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/515708.html
標籤:C#