C#,获取要在数组中使用的用户输入
问题描述:
在这段代码中,我试图编写要求我制作一个小菜单,并且A要取5个整数,而B要显示它们,C和D是//因为我不喜欢不得不对这些部分进行编码,但由于某种原因我不能正确输入整数,并且要用B显示它们。我的主要问题是如何在loadarray中获得5个用户输入然后使用在displayarray中的那个数组?
In this code I am attempting to write requires that I make a small menu, and for A to take 5 integers, and B to display them, C and D are // out because I don't have to code those sections yet, but for some reason I can't get the integers to input right, and for them to be displayed with B. My main question is how can I get 5 user inputs inside of loadarray and then use that array in displayarray?
static void Main(string[] args)
{
char choice;
int[] Num = new interger[5];
do
{
Console.Clear();
Choice = Menu();
switch (choice)
{
case 'A':
case 'a':
lArray(Num);
Console.ReadLine();
break;
case 'B':
case 'b':
dArray(Num);
Console.ReadLine();
break;
case 'C':
case 'c':
// Console.WriteLine("Sum: {0}", cSum(Num));
Console.ReadLine();
break;
case 'D':
case 'd':
// Console.WriteLine("Average: {0}", cAverage(Num));
Console.ReadLine();
break;
case 'Z':
case 'z':
break;
default:
Console.WriteLine("Invalid number!");
break;
}
}
while (choice != 'Z' && choice != 'z');
}
static char Menu()
{
char Input;
string[] strOptions = new string[] {
"A. Add num",
"B. Display num",
"C. Output sum ",
"D. Output average",
"z. Exit"
};
Console.WriteLine("What would you like to do?");
foreach(string strValue in strOptions)
{
Console.WriteLine(strValue);
}
do
{
Console.Write("Please select from A to Z: ");
Input = Console.ReadKey().KeyChar;
Console.WriteLine();
}
while ((Input < 'A' || Input > 'Z') && (Input < 'a' || Input > 'z'));
return Input;
}
static int lArray(int[] array)
{
int[] newArray = new int[5];
答
您正在创建一个存储在名为newArray
的局部变量中的新数组。然后,您将用户输入存储在局部变量中,并且永远不会触摸您传入的数组。当您的方法返回时,您输入的所有数字都将被丢弃。
更改方法以将您传入的数组中的数字存储为参数(array
)。
您还应该考虑如果用户输入无法转换为整数的内容会发生什么。目前,您的代码将抛出异常并崩溃。使用 int.TryParse [ ^ ]会让你优雅地处理错误:
You're creating a new array stored in a local variable callednewArray
. You then store the user input in the local variable, and never touch the array you passed in. When your method returns, all of the numbers you've entered are thrown away.
Change the method to store the numbers in the array you've passed in as a parameter (array
) instead.
You should also consider what happens if the user enters something that can't be converted to an integer. Currently, your code will throw an exception and crash. Using int.TryParse[^] would let you handle the error gracefully:
static void loadArray(int[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.Write("Enter a number: ");
string input = Console.ReadLine();
if (!int.TryParse(input, out array[i])
{
// Tell the user something went wrong:
Console.WriteLine("Sorry, '{0}' is not a valid number.", input);
// Don't move to the next array element:
i--;
}
}
}