我完全失去了......逻辑似乎设置正确但是while语句中的“响应”表示它在当前上下文中不存在。我在这里搜索,似乎在这种情况下似乎找到了相同的问题。问题是转向方法吗?
do
{
Console.WriteLine("enter a number between 1 and 5");
int x = Convert.ToInt32(Console.ReadLine());
Random r = new Random();
int rr = r.Next(1, 5);
Console.WriteLine("Do you want to continue? Please select yes or no.");
string response = Convert.ToString(Console.ReadLine());
} while (response == "yes");
答案 0 :(得分:6)
在一个范围内声明的变量(通常是一组大括号{ ... }
)在该范围之外无法访问。您已在循环中声明response
。您需要在循环之外声明response
。
您还希望在使用String.Trim()
进行比较之前修剪字符串中的空格。否则最后会有一个换行符(\n
),导致你的比较失败。
string response;
do {
//...
response = Console.ReadLine().Trim();
} while (response == "yes");
答案 1 :(得分:1)
您的响应变量不在循环的上下文中。只需将变量声明移到循环外部,如下所示:
string response = String.Empty;
do
{
Console.WriteLine("enter a number between 1 and 5");
int x = Convert.ToInt32(Console.ReadLine());
Random r = new Random();
int rr = r.Next(1, 5);
Console.WriteLine("Do you want to continue? Please select yes or no.");
response = Convert.ToString(Console.ReadLine());
} while (response == "yes");
答案 2 :(得分:0)
可能有助于封装这一点。怎么样:
static void Main(string[] args)
{
Random rand = new Random();
do
{
Write("enter a number between 1 and 5");
string response = Console.ReadLine();
int x = 5;
if (Validate(response, "1-5")) int.TryParse(response, out x);
Write(rand.Next(0,x));
Write("Do you want to continue? Please select yes or no.");
} while (Validate(Console.ReadLine().ToLower(), "yes"));
}
static void Write(string s) => Console.WriteLine(s);
static bool Validate(string s, string Pattern) => Regex.Match(s, Pattern).Success;