【问题标题】:Array out of bounds in for loopfor循环中的数组越界
【发布时间】:2018-04-12 07:49:43
【问题描述】:
//dice throws to arrays
        int throws = 1;
        int[] oneDice = new int[throws];
        int[,] twoDice = new int[throws,throws];

        Console.WriteLine("Number of throws: ");
        throws = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Trows one dice "+throws+" times: ");
        for (int i = 0; i < throws; i++)
        {
            Random random = new Random();
            oneDice[i] = random.Next(6);
            Console.WriteLine(oneDice[i]);

        }

它说我的数组 oneDice 超出范围,但我不明白为什么.. 请帮我弄清楚。

【问题讨论】:

  • 您正在创建长度为 1 的数组。您应该在创建数组之前阅读投掷次数。

标签: arrays for-loop random


【解决方案1】:

你做错的是用 1 声明你的数组,然后你正在改变你的变量。更改变量不会更改您的数组声明,因此您将不得不承担索引超出范围的错误。

另外,你需要把random变量声明放在loop之前,这样每次都能得到不同的结果。

试试这个

Console.WriteLine("Number of throws: ");
        int throws = Convert.ToInt32(Console.ReadLine());
        int[] oneDice = new int[throws];
        int[,] twoDice = new int[throws, throws];
        Console.WriteLine("Trows one dice "+throws+" times: ");
        Random random = new Random();
        for (int i = 0; i<throws; i++)
        {
           // Random random = new Random();
        oneDice[i] = random.Next(6);
            Console.WriteLine(oneDice[i]);

        }

【讨论】:

  • @Louise Bjerre Thomsen 你试过上面的代码了吗?
  • 非常感谢!确实有帮助^^
【解决方案2】:
        Console.WriteLine("Number of throws: ");
        int throws = Convert.ToInt32(Console.ReadLine());
        int[] oneDice = new int[throws];
        int[,] twoDice = new int[throws, throws];
        Console.WriteLine("Throws one dice " + throws + " times: ");
        Random random = new Random();

        for (int i = 0; i < throws; i++)
        {
            oneDice[i] = random.Next(6);
            Console.WriteLine(oneDice[i]);
        }

错误是由于您最初将数组的长度定义为 1 造成的。先读取 throws 的数量再创建数组就没有问题了。

【讨论】:

    最近更新 更多