如何让用户从Console输入任意数量的变量

这是我制作的代码,它会滚动两个骰子直到出现一对。 我的问题是,有没有办法让用户输入他/她想要的任意数量的骰子?

我不想创建50个骰子。 如果我使用数组或列表,我会遇到同样的问题。 我必须将每个数组部分分配给numbergen 50次或更多次。 也许有一些我想念的东西?

static void Main(string[] args) { Random numbergen = new Random(); int dice1=0; int dice2=1; for (int counter = 0; counter <= 1; counter++) { while (dice1 != dice2) { dice1 = numbergen.Next(1, 7); dice2 = numbergen.Next(1, 7); if (dice1 == dice2) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(dice1 + "\t" + dice2); counter++; dice1 = 0; dice2 = 1; } else if (dice1 != dice2) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(dice1 + "\t" + dice2); } if (counter ==1 ) { break; } } } Console.ReadLine(); } 

这是一个所有模具必须匹配的版本。

 using System; namespace Dicey { class Program { static void Main(string[] args) { int numberOfDice; // check for and retrieve the number of dice the user wants. if (args.Length != 1 || !int.TryParse(args[0], out numberOfDice)) { Console.WriteLine("Please provide the number of dice."); return; // exit because arg not provided } // Must have at least one and set some arbitrary upper limit if (numberOfDice < 1 || numberOfDice > 50) { Console.WriteLine("Please provide a number of dice between 1 and 50"); return; // exist because not in valid range } var dice = new int[numberOfDice]; // create array of die (ints) var rand = new Random(); var match = false; // start with false (match not found yet) while (!match) // loop until match becomes true { var message = string.Empty; match = true; // assume match until something doesn't match for (var i = 0; i < numberOfDice; i++) { // initialize dice at index i with the random number dice[i] = rand.Next(1, 7); // build the message line to write to the console message += dice[i]; // first add the die's number if (i < numberOfDice - 1) message += "\t"; // if not at the end, add a tab // check if the previous die (except for the first of course) has a different number if (i > 0 && dice[i - 1] != dice[i]) match = false; // uh oh, not all match. we have to keep going } // print out the message Console.ForegroundColor = match ? ConsoleColor.Yellow : ConsoleColor.White; Console.WriteLine(message); } Console.ReadLine(); } } } 

如果要存储用户指定的多个整数,那么最简单的方法是使用类似int x[z]的数组,其中z是用户指定的数字,或者更好的是,创建一个列表以Listforms的整数,您可以根据用户输入的数字添加整数。

你不会遇到同样的问题,就像你在执行numbergen时有很多不同的变量一样,因为你可以让你的循环遍历你的列表或数组,给它们一个由numbergen分配的值。

试试这个,让用户输入一些骰子将它存储在变量中,然后创建一个大小的数组。