[英]c# For loop through 2D array exception unhandled, Index out of bounds
Apologies for the beginner question but I am struggling to find an answer as to why I get an exception unhandled error after the first For loop. 对于初学者的问题表示歉意,但我一直在努力寻找答案,以了解为什么在第一个For循环后出现异常未处理错误。 It runs through the loop once, asking me the three questions, and then the program stops.
它循环运行一次,问我三个问题,然后程序停止。 C#
C#
(I am trying to teach myself as my teachers aren't going through much at all, so sorry again) (我正在尝试自学,因为我的老师一点都没经历,所以再次抱歉)
Console.WriteLine("How many people do you have to enter?");
int numPeople = int.Parse(Console.ReadLine());
string[,] data = new string[numPeople,2];
for (int i = 0; i < numPeople; i++)
{
Console.WriteLine("Enter a Name:");
data[i,0] = Console.ReadLine();
Console.WriteLine("Enter " + data[i,0] +"'s Age:");
data[i,1] = Console.ReadLine();
Console.WriteLine("Enter " + data[i,0] + "'s class:");
data[i,2] = Console.ReadLine();
}
for (int v = 0; v < numPeople; v++)
{
for (int x = 0; x < 3; x++)
{
Console.WriteLine(data[v,x] + "\t");
}
}
Console.ReadLine();
In this part 在这部分
string[,] data = new string[numPeople,2];
you define that your array size is 2 and the error it gives is Index was outside the bounds of the array.
您定义您的数组大小为2,并且给出的错误是
Index was outside the bounds of the array.
So you change the 所以你改变
string[,] data = new string[numPeople,2];
to 至
`string[,] data = new string[numPeople,3];
Read more about the subject from https://www.geeksforgeeks.org/c-sharp-arrays/ and try to understand how the arrays work. 从https://www.geeksforgeeks.org/c-sharp-arrays/阅读有关该主题的更多信息,并尝试了解数组的工作原理。 :)
:)
also if you are using Visual Studio read about the Break point debugging https://docs.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2017 另外,如果您使用的是Visual Studio,请阅读有关调试断点的信息https://docs.microsoft.com/zh-cn/visualstudio/debugger/using-breakpoints?view=vs-2017
Happy coding! 编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.