C#用户输入的int数组 [英] C# user input int to array
问题描述
我要求用户输入5个号码,并将其存储到一个数组,所以我可以在一个方法,从每个阵列发送的价值观和减去5个号码。当我使用:
I'm asking the user to input 5 numbers and store it into an array so I can send the values in a method and subtract 5 numbers from each array. When I use the:
for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}
它说我不能转换INT []为int。我在我的节目有点生疏。我也不知道如何从主发送数组值的方法。
It says I can't convert int[] to int. I'm a little rusty in my programming. I also don't know how to send the array values from the main to the method.
推荐答案
您正在分配从控制台的字符串输入到一个int数组。这是错误的,原因有二:
You're assigning the string input from the Console to an array of int. This is wrong for two reasons:
-
INT
阵列(INT []
)的int类型的集合
。 - 您正在从控制台获取的值不是一个
INT
,需要首先分析。
int
arrays (int[]
) are a collection ofints
.- The value you're getting from the Console isn't an
int
and needs to be parsed first.
这是一个轻微的分流,但我也不会你应该使用数组认为。阵列通常在C#显著少功能比内置的列表&LT; T&GT;
。 (所有摇滚歌星附和 href=\"http://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which\">)有人说,没有理由在所有使用数组 - 我不会走那么远,但我认为这种使用情况这将是一个更容易只是将项目添加到列表
比5分配的空间和通过索引初始化值。
This is a slight diversion, but I also don't think you should be using an array. Arrays generally have significantly less function in C# than the built-in List<T>
. (All the rockstars chime in here) Some people say there's no reason to use arrays at all - I won't go that far, but I think for this use case it'll be a lot easier to just add items to a List
than to allocate 5 spaces and initialize values by index.
无论哪种方式,你应该使用 int.TryParse()
,而不是 int.Parse()
,因为你会立即得到一个例外,如果你不检查,如果用户输入的是解析的,以 INT
。因此,例如code采取字符串中从用户是这样的:
Either way, you should use int.TryParse()
, not int.Parse()
, given that you'll immediately get an exception if you don't check if the user input was parseable to int
. So example code for taking in strings from the user would look like this:
List<int> userInts = new List<int>();
for (int i = 0; i < 5; i++)
{
string userValue = Console.ReadLine();
int userInt;
if (int.TryParse(userValue, out userInt))
{
userInts.Add(userInt);
}
}
如果您仍想使用数组,或者如果你有,只需更换列表&LT; INT&GT; userInts
...与 INT [] = userInts新INT [5];
,并替换 userInts.Add(userInt )
与 userInts [I] = userInt;
If you'd still like to use the array, or if you have to, just replace List<int> userInts
... with int[] userInts = new int[5];
, and replace userInts.Add(userInt)
with userInts[i] = userInt;
.
这篇关于C#用户输入的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!