2016-12-31 93 views
1

我在这里完全失败......逻辑似乎设置正确,但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"); 
+5

您在循环内部声明了'response',这就是它存在的地方通常,新的缩进级别会创建一个新的块范围..您可能还想为整个循环创建一个随机实例,而不是每次迭代 – Plutonix

+2

如果你在循环内部定义了'response',它应该如何在它外面检查它?你必须定义'字符串response'前环 – UnholySheep

+1

响应确实超出{}范围不可见,声明它之前做 –

回答

6

变量不是该范围的可访问的外部。您已在内声明response循环。您需要在循环之外声明response

你也想比较它,使用前String.Trim()从字符串修剪空白。否则,最后会出现换行符(\n),导致比较失败。

string response; 

do { 
    //... 

    response = Console.ReadLine().Trim(); 
} while (response == "yes"); 
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

这个答案是什么添加,这还没有说明? –

+1

无需为每次迭代创建一个新的随机;这是一个坏习惯。不需要Convert.ToString – Plutonix

+0

@Plutonix - 你是对的,但只有在大括号内部使用的局部变量应该在大括号内声明,以限制范围。编译器非常聪明,可以使其尽可能高效。 – Joe

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; 
+0

每次你想要一个随机数时创建一个新的Random对象是不正确的。 –

+0

我希望你们投票支持所有其他人,因为我只使用他们提供的代码。无论如何,我会纠正它,即使这对处理时间或内存没有影响,因为GC应该收集这些数据,因为它超出范围,每个呼叫和系统空闲等待用户响应并根据需要进行处理。 –

+0

我确实相信你是不正确的,即使我相信我遇到了你的建议。遵循适当的面向对象,将随机化封装成像我一样的方法会更好。循环应尽可能保持干净,因为它的目的是收集用户输入,输入的处理应该在别处处理。对每个方法的调用创建一个新的Random是可以的,但不能在循环内部创建,因为这会阻止GC进行收集,因为引用永远不会被释放。然而,在它自己的方法中,它们将随着每次调用和返回值而被释放。 –