【问题标题】:for loop throwing out of range exceptionfor循环抛出超出范围异常
【发布时间】:2013-09-28 10:40:14
【问题描述】:

错误是

索引超出范围异常

并且在for循环的第一行:

for (i = (int)start, j = 0; i <= (int)end; i++, j++)
{  // Since linear relationships...
    idealWeights[0, j] = (female += 3.5);   **ERROR HERE ON THIS LINE**
    idealWeights[1, j] = (male += 4.0);
}

txtStart 和 txtEnd 中的值是: txt开始 = 36 txtEnd = 96

代码如下:

using System;
using System.Windows.Forms;

public class frmMain : Form
{
    private TextBox txtStart;
    private TextBox txtEnd;
    private ListBox lstResults;
    private Button btnClose;
    private Label label1;
    private Label label2;
    private Button btnCalc;

    private void InitializeComponent()
    {
            this.btnCalc = new System.Windows.Forms.Button();
            this.txtStart = new System.Windows.Forms.TextBox();
            this.txtEnd = new System.Windows.Forms.TextBox();
            this.lstResults = new System.Windows.Forms.ListBox();
            this.btnClose = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // btnCalc
            // 
            this.btnCalc.Location = new System.Drawing.Point(26, 197);
            this.btnCalc.Name = "btnCalc";
            this.btnCalc.Size = new System.Drawing.Size(75, 23);
            this.btnCalc.TabIndex = 0;
            this.btnCalc.Text = "Ca&lculate";
            this.btnCalc.UseVisualStyleBackColor = true;
            this.btnCalc.Click += new System.EventHandler(this.btnCalc_Click);
            // 
            // txtStart
            // 
            this.txtStart.Location = new System.Drawing.Point(172, 12);
            this.txtStart.Name = "txtStart";
            this.txtStart.Size = new System.Drawing.Size(100, 20);
            this.txtStart.TabIndex = 1;
            // 
            // txtEnd
            // 
            this.txtEnd.Location = new System.Drawing.Point(172, 38);
            this.txtEnd.Name = "txtEnd";
            this.txtEnd.Size = new System.Drawing.Size(100, 20);
            this.txtEnd.TabIndex = 2;
            // 
            // lstResults
            // 
            this.lstResults.FormattingEnabled = true;
            this.lstResults.Location = new System.Drawing.Point(26, 96);
            this.lstResults.Name = "lstResults";
            this.lstResults.Size = new System.Drawing.Size(246, 95);
            this.lstResults.TabIndex = 3;
            // 
            // btnClose
            // 
            this.btnClose.Location = new System.Drawing.Point(197, 197);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(75, 23);
            this.btnClose.TabIndex = 4;
            this.btnClose.Text = "&Close";
            this.btnClose.UseVisualStyleBackColor = true;
            // 
            // label1
            // 
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.label1.Location = new System.Drawing.Point(23, 12);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(143, 20);
            this.label1.TabIndex = 5;
            this.label1.Text = "Start:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label2
            // 
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.label2.Location = new System.Drawing.Point(23, 38);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(143, 20);
            this.label2.TabIndex = 6;
            this.label2.Text = "End:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // frmMain
            // 
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.lstResults);
            this.Controls.Add(this.txtEnd);
            this.Controls.Add(this.txtStart);
            this.Controls.Add(this.btnCalc);
            this.Name = "frmMain";
            this.ResumeLayout(false);
            this.PerformLayout();

    }

    public frmMain()
    {
        InitializeComponent();
    }

    public static void Main()
    {
        frmMain main = new frmMain();
        Application.Run(main);
    }

    const double MININCHES = 36;
    const double MAXINCHES = 96;

    private void btnCalc_Click(object sender, EventArgs e)
    {
        bool flag;
        int i;
        int j;
        double start;
        double end;
        double male;
        double female;
        double[,] idealWeights;
        string buff;

        //============================== Input ===============================================
        flag = double.TryParse(txtStart.Text, out start);  // Table start
        if (flag == false)
        {
            MessageBox.Show("Numeric only.");
            txtStart.Focus();
            return;
        }

        flag = double.TryParse(txtEnd.Text, out end);  // Table end
        if (flag == false)
        {
            MessageBox.Show("Numeric only.");
            txtEnd.Focus();
            return;
        }

        //============================= Validate input ==============================================
        if (start < MININCHES || start > MAXINCHES)  // Check table limits
        {
            MessageBox.Show("Table can only span " + MININCHES.ToString() + " to " +
                MAXINCHES + " inches.");
            txtStart.Focus();
            return;
        }
        if (end < MININCHES || end > MAXINCHES)
        {
            MessageBox.Show("Table can only span " + MININCHES.ToString() +
                " to " + MAXINCHES + " inches.");
            txtEnd.Focus();
            return;
        }
        if (end <= start)       // Can we display anything
        {
            MessageBox.Show("Starting value must be less than ending value");
            txtStart.Focus();
            return;
        }
        // Define the array for table data
        idealWeights = new double[2, (int)(end - start) + 1];

        //=============================== Process ====================================================
        start--;                // This is the new line
        female = 3.5 * start - 108;  // Set initial table values
        male = 4.0 * start - 128;

        for (i = (int)start, j = 0; i <= (int)end; i++, j++)
        {  // Since linear relationships...
            idealWeights[0, j] = (female += 3.5);
            idealWeights[1, j] = (male += 4.0);
        }
        //================================ Display step ==============================================
        for (i = (int)start, j = 0; i <= (int)end; i++, j++)
        {
            buff = String.Format("{0,5}{1,15}{2,15}", i, idealWeights[0, j], idealWeights[1, j]);
            lstResults.Items.Add(buff);
        }
    }
}

我对编程很陌生,所以我在这里有点迷路,这段代码来自一本书,书中还没有任何错误。所以希望错误不是很复杂,因为我仍然只是输入大量代码并阅读代码以尝试理解它。

【问题讨论】:

  • 用调试器单步调试你的代码;在这一点上应该是相当明显的。
  • 如错误所述,数组索引超出范围。您正在尝试引用不在数组中的元素。发生这种情况时检查j 的值,并检查数组的内容。
  • 请给出您放入 txtStart 和 txtEnd 的值。
  • @KaiHartmann txtStart = 36 txtEnd = 96

标签: c# exception runtime-error indexoutofboundsexception


【解决方案1】:

您没有对 j 变量进行任何绑定检查。它显然超过了第二个数组元素的大小。正如 Servy 在我们的 cmets 中指出的那样,这是一个常见的错误。我已调整代码以从 中删除 =

for 行需要看起来像...

for (i = (int)start, j = 0; i < (int)end; i++, j++)

【讨论】:

  • i 的检查是为了确保j 的增量不会超过应有的值,所以不,他不需要添加这样的东西。
  • @Servy 但这不是正在发生的事情。我已将此代码粘贴到运行中。 J 正在爆炸,因为 j == 数组的上限。我不能说我应该做什么检查;因为这是一些非常糟糕的代码。无论如何,这就是正在发生的事情。
  • i 上的检查可能确实不正确,需要更新,但关键是这些应该修复。如果您在j 上添加新的检查,那么您只是违背了检查i 的目的,它专门用于对数组进行边界检查。我同意代码写得不好,但是如果您要更改它,请一路走下去。如果您想对j 进行边界检查,那么只需完全删除两个循环变量代码并使用更传统的for 循环。
  • 对于您的编辑,您现在比数组的大小小一,而不是 OP 的代码多一。
  • @Servy 我同意。它使对 i 的检查变得多余。一开始就不需要它们。这是一个非常糟糕的 C# 示例;在惯用语和逻辑上。基于这个代码示例,我当然不会向任何人推荐这本书。
猜你喜欢
  • 2011-09-07
  • 2013-11-18
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多