【发布时间】:2020-10-07 01:05:03
【问题描述】:
我是编码新手,只是把它作为一种爱好,我正在解决一些 CodeAbbey 问题来练习。
我正在尝试获取由空格和换行符分隔的数字组并填充一个多维数组,以便我可以对这些数字执行一些数学运算。我还没有进入数学部分,还在尝试将数据放入数组中。
数据集示例:
5(这是数据集的数量)
(以下是实际数据)
7899743 906
6574065 -1243290
5441 1320
9965047 86
4781 1934
我的代码如下:
namespace Rounding
{
class Program
{
static void Main(string[] args)
{
// declare variables
// n asks user for number of array columns
// raw takes the numbers seperated by new lines
int n = int.Parse(Console.ReadLine());
string[] raw = Console.ReadLine().Split('\n');
int[,] numbers = new int [n,2];
// loop through raw array and split the numbers and add them to multidimentional array
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
numbers [i, j] = Convert.ToInt32(raw[n].Split(' '));
}
}
// display data from multidimentional array (for testing)
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine(numbers[i,j]);
}
}
}
}
}
程序应等待用户输入数据集的数量,然后再次等待实际数据,然后使用该数据填充数组。
我收到的调试消息是在numbers [i, j] = Convert.ToInt32(raw[n].Split(' '));
它说
System.IndexOutOfRangeException: '索引超出范围 数组。'
任何关于我做错了什么的指导将不胜感激。
【问题讨论】:
-
这将取决于您在运行时在控制台中输入的值,例如输入 0 然后输入 8 它将起作用,输入 1 然后输入 8 则不会(因为数组为零基于,它现在正在寻找第二个值并且没有)。
-
您想用在数组 raw 中输入的值填充 n 行和 2 列的数组。但是如果用户输入的数字少于 n x 2 怎么办 - 你显然会得到一个超出范围异常的索引。
-
我不需要假设用户会在这种情况下输入错误的金额。我只想让代码正常工作,但遇到了麻烦,无法弄清楚我做错了什么。如果我玩弄数字,比如先放 1,然后放 8 8,我会收到以下错误: System.InvalidCastException: 'Unable to cast object of type 'System.String[]' to type 'System.IConvertible'。不知道那是什么