使用C#控制台创建一个Random Stats应用程序,要求用户输入一个数字。然后它应该生成0到9之间的许多随机数,然后显示每个数字的出现次数。应用程序输出应输出:
Enter a number: 500
Number Occurences
0 58
1 56
2 47
3 49
4 49
5 55
6 49
7 59
8 36
9 42
1. Assign New Set of Integers
2. Exit
这是我到目前为止所得到的:
string input;
int userNumber;
Console.Write("Enter a number: ");
input = Console.ReadLine();
userNumber = int.Parse(input);
Console.WriteLine("\n" + "Number Occurrences");
int[] number = new int[10];
int[] numberTwo = new int[userNumber];
Random randNum = new Random();
for (int counter = 0; counter < userNumber; counter++)
{
numberTwo[counter] = randNum.Next(10);
if (numberTwo[counter] == 0)
{
number[0]++;
}
if (numberTwo[counter] == 1)
{
number[1]++;
}
if (numberTwo[counter] == 2)
{
number[2]++;
}
if (numberTwo[counter] == 3)
{
number[3]++;
}
if (numberTwo[counter] == 4)
{
number[4]++;
}
if (numberTwo[counter] == 5)
{
number[5]++;
}
if (numberTwo[counter] == 6)
{
number[6]++;
}
if (numberTwo[counter] == 7)
{
number[7]++;
}
if (numberTwo[counter] == 8)
{
number[8]++;
}
if (numberTwo[counter] == 9)
{
number[9]++;
}
}
for (int numberThree = 0; numberThree <= 9; numberThree++)
{
Console.WriteLine(numberThree + "\t" + number[numberThree]);
}
Console.ReadKey();
正如你所看到的那样,我的老师问题的第一部分已经工作了,但是当涉及到我必须添加一个功能的用户可能输入1以获得输入的下一部分时,我似乎感到困惑新号码或按2退出程序。 (该程序在控制台btw中)
答案 0 :(得分:0)
我将它包装在while循环中,并将您的逻辑移动到一个单独的方法。
shell
请注意,如果用户从不按2,这将是一个无限循环。 此外,还有 int.Parse ,因为它可能会导致您的应用崩溃。尝试使用 int.TryParse 。
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
正如评论中所提到的,您可以通过使用字典来优化代码。
class Program
{
static void Main(string[] args)
{
EnterNumber();
Console.ReadKey();
bool doEnd = false;
while (!doEnd)
{
Console.WriteLine("");
Console.WriteLine("1.Assign New Set of Integers");
Console.WriteLine("2.Exit");
ConsoleKeyInfo info = Console.ReadKey();
int val;
if (!int.TryParse(info.KeyChar.ToString(), out val))
{
// Error handling...
}
switch (val)
{
case 1: EnterNumber();
break;
case 2:
doEnd = true;
break;
}
}
}
private static void EnterNumber()
{
string input;
int userNumber;
Console.Write("Enter a number: ");
input = Console.ReadLine();
userNumber = int.Parse(input);
Console.WriteLine("\n" + "Number Occurrences");
int[] number = new int[10];
int[] numberTwo = new int[userNumber];
Random randNum = new Random();
for (int counter = 0; counter < userNumber; counter++)
{
numberTwo[counter] = randNum.Next(10);
if (numberTwo[counter] == 0)
{
number[0]++;
}
if (numberTwo[counter] == 1)
{
number[1]++;
}
if (numberTwo[counter] == 2)
{
number[2]++;
}
if (numberTwo[counter] == 3)
{
number[3]++;
}
if (numberTwo[counter] == 4)
{
number[4]++;
}
if (numberTwo[counter] == 5)
{
number[5]++;
}
if (numberTwo[counter] == 6)
{
number[6]++;
}
if (numberTwo[counter] == 7)
{
number[7]++;
}
if (numberTwo[counter] == 8)
{
number[8]++;
}
if (numberTwo[counter] == 9)
{
number[9]++;
}
}
for (int numberThree = 0; numberThree <= 9; numberThree++)
{
Console.WriteLine(numberThree + "\t" + number[numberThree]);
}
}
}