2017-02-12 54 views
0

我试图将控制台背景颜色设置为随机颜色,但始终返回洋红色。我需要改变什么来解决这个问题。谢谢!C# - 为什么每次都设置为洋红色?

using System; 

    namespace ConsoleApplication 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      Random random = new Random(); 
      int randomInt = random.Next(0, 6); 
      while(randomInt < 7) 
      { 
       Console.BackgroundColor = ConsoleColor.Red; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Blue; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Cyan; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Green; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Red; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Yellow; 
       randomInt++; 
       Console.BackgroundColor = ConsoleColor.Magenta; 
       randomInt++; 
      } 
     } 
    } 
} 
+2

使用调试器和步骤通 - 你应该看到你的错误... –

+0

我不明白的问题 - 即得到由'while'循环设置为洋红色最后一种颜色。你可能想要使用不同的结构,例如'if'或'switch'' case' – UnholySheep

+1

显然你想创建某种[Duff's设备](https://en.wikipedia.org/wiki/Duff% 27s_device),希望'randomInt'在'while'中的每条指令之后被重新评估为'<7',并且它会在发生时自动退出'while'。这不是它的工作原理。 – GSerg

回答

3

你误会了我相信循环的概念,它可能不是你使用的工具。 要随机化颜色,您必须将它们与一个数字相关联,然后选取一个数字并选择相关的颜色。

ConsoleColor是一个枚举,这意味着每个值已经与一个数字关联。您可以使用this question中描述的方法从枚举中选择一个随机值。

如果您只想从枚举中只有几种颜色,您将不得不创建自己想要的值的数组,并从该数组中选择一个值。

这里是一个如何从数组中选择一个随机项的例子。

Random random = new Random(); 
ConsoleColor[] colors = new ConsoleColor[] { ConsoleColor.Red, ConsoleColor.Blue }; 
var myRandomColor = colors[random.Next(0, colors.Length)]; 
0

你实际上是设置所有颜色和最后洋红。我认为如果你想有条件地设置颜色,你应该使用if或case语句。如果你对此有何评论品红assignmnent你总是会得到黄色背景

 while(randomInt < 7) 
     { 
      Console.BackgroundColor = ConsoleColor.Red; 
      randomInt++; 
      Console.BackgroundColor = ConsoleColor.Blue; 
      randomInt++; 
      Console.BackgroundColor = ConsoleColor.Cyan; 
      randomInt++; 
      Console.BackgroundColor = ConsoleColor.Green; 
      randomInt++; 
      Console.BackgroundColor = ConsoleColor.Red; 
      randomInt++; 
      Console.BackgroundColor = ConsoleColor.Yellow; 
      randomInt++; 
      //Console.BackgroundColor = ConsoleColor.Magenta; 
      //randomInt++; //THIS WILL ALWAYS BE YELLOW 
     } 

我认为你需要的是一个case语句:

switch(randomInt) 
{ 
    case 0: 
     Console.BackgroundColor = ConsoleColor.Red; 
     break; 
    case 1: 
     Console.BackgroundColor = ConsoleColor.Blue; 
     break; 
    ///....AND SO ON 
} 
-1

什么你也可以做的是隐式解析INT到ConsoleColor。

像这样:

Console.BackgroundColor = (ConsoleColor)randomInt;

有了这个,你必须改变你randomInt的范围。我建议查找枚举和ConsoleColor的后台代码。

+1

此代码容易出错。如果枚举不包含随机数? –

相关问题