使用大小无法在C#中工作的用户输入填充数组

时间:2016-01-27 19:57:34

标签: c#

我想让用户定义数组的大小及其中的所有数字,所以这就是我的想法:

int []arr={0};
Console.WriteLine("Please enter the size of the array:");
size = Console.Read();

for(int i=0; i<size; i++)
{
    Console.WriteLine("Please enter the next number in the array, it's position is: " + i);
    arr[i] = Console.Read();
}

当我尝试运行时,它会给我一个超出范围的指数&#39;错误。 如果有人能指出我做错了什么,我会非常感激。

编辑: 在答案之后我稍微更改了代码,现在它看起来像这样:

Console.WriteLine("Please enter the size of the array:");
input = Console.ReadLine();
size = int.Parse(input);
int[] arr = new int[size];

for(int i=0; i<size; i++)
{
    string b;
    Console.WriteLine("Please enter the next number in the array, it's position is: " + i);
    b = Console.ReadLine();
    arr[i] = int.Parse(b); 
}

所以现在数组可以更大,内部的数字也更大,再次感谢帮助!

3 个答案:

答案 0 :(得分:3)

您需要在从用户输入后初始化数组:

Console.WriteLine("Please enter the size of the array:");
int size = int.Parse(Console.ReadLine()); //you need to parse the input too
int[] arr = new int[size];

for(int i=0; i < arr.Length; i++)
{
    Console.WriteLine("Please enter the next number in the array, it's position is: " + i);
    arr[i] = int.Parse(Console.ReadLine()); //parsing to "int"
}

注意:您不应该使用Console.Read()它会在评论中提到的字符ASCII返回SzabolcsDézsi。您应该使用Console.ReadLine()代替。

答案 1 :(得分:0)

您需要重新实例化数组对象:

int []arr={0};
Console.WriteLine("Please enter the size of the array:");
size = Console.Read();
arr=new int[size];
for(int i=0; i<size; i++){
   Console.WriteLine("Please enter the next number in the array, it's position is: " + i);
   arr[i] = Console.Read();
            }

答案 2 :(得分:0)

仍然不是最理想的,但这会阻止用户输入非数字数据。每次都保持提示,直到数据有效。

{
 "error": {
  "errors": [
   {
    "domain": "youtube.commentThread",
    "reason": "forbidden",
    "message": "The comment thread could not be created due to insufficient permissions. The request might not be properly authorized.",
    "locationType": "other",
    "location": "body"
   }
  ],
  "code": 403,
  "message": "The comment thread could not be created due to insufficient permissions. The request might not be properly authorized."
 }
}

我不会使用Console.WriteLine("Please enter the size of the array:"); int size; while(!int.TryParse(Console.ReadLine(), out size)) { Console.WriteLine("Please enter the size of the array:"); } var arr = new int[size]; for (int i = 0; i < size; i++) { Console.WriteLine("Please enter the next number in the array, it's position is: " + i); int currentElement; while (!int.TryParse(Console.ReadLine(), out currentElement)) { Console.WriteLine("Please enter the next number in the array, it's position is: " + i); } arr[i] = currentElement; } ,因为这样你一次只能读一个字符。因此,对于数组大小,最多只能读取0-9,如果输入15,则数组的长度为1,下一个Console.Read将读取5并填入第一个元素。