【问题标题】:how can i assign value to an array in one method and call from another method如何在一种方法中为数组赋值并从另一种方法调用
【发布时间】:2021-09-07 23:11:39
【问题描述】:

我试图通过调用带参数的方法来在 main 方法中为数组赋值 我想从同一个类中的另一种方法中读取它,但在地雷中它只读取数组的最后一个元素。这是一个例子

public void array(int x)
    {
         for(int i = 0; i < 5; i++)
         {
            array1[i] = x;
         }          
    }
public void readarray()
    {
        for(int i = 0; i < 5; i++)
        {
            Console.WriteLine("     " + array1[i]);
        }
    }
}

在主要方法中

int z;
        for(int i = 1; i < 6; i++)
        {
          Console.Write($"Enter e values for index {i}:");
            z = int.Parse(Console.ReadLine());
            obj.array(z);
        }           
        obj.readarray();




   

【问题讨论】:

  • 欢迎使用 stackoverflow。我推荐taking the tour,以及阅读how to ask a good questionwhat's on topic
  • 我很困惑这段代码应该做什么。我确实注意到,在第二个代码块中,您将从 1 变为 6,而不是从 0 变为 5
  • 好吧,你的array-方法用提供的参数的值覆盖了整个数组中的每个元素。当您在循环中调用该方法时,您会一次又一次地有效地覆盖前一个循环的内容,直到到达最后一次迭代。我想您只想在每次迭代中设置一个 特定 元素,不是吗?
  • @DavidG 在这里没关系。它仍然是 5 次迭代,其中索引实际上并不重要。重要的是整个数组被当前值覆盖(z in main,x in array(x))。
  • @Fildor 我知道,我只是指出不一致

标签: c# arrays methods


【解决方案1】:

有关您所经历的解释,请参见 cmets:

public void array(int x)  // Every time this method is called ...
{
    for(int i = 0; i < 5; i++) // you set for index 0 to 4 ...
    {
       array1[i] = x;          // array[index] = x 
       /* so, result is
          array1[0] = x
          array1[1] = x
          array1[2] = x
          array1[3] = x
          array1[4] = x
        */
    }          
}

public void readarray()
{
    for(int i = 0; i < 5; i++)
    {
        Console.WriteLine("     " + array1[i]); // ALL of your array1[i] are x from
                                                // most recent call to array(x) !
    }
}

所以,...

for(int i = 1; i < 6; i++)
{
    Console.Write($"Enter e values for index {i}:");
    z = int.Parse(Console.ReadLine());
    obj.array(z); // <= the whole array[0] to array[4] is now == `z`
}           
obj.readarray(); // will print last value of z for all indices of array!

有一些方法可以解决这个问题。

例如,您可以传递要设置的特定索引:

void array(int index, int value){ array1[index] = value; }

并像这样使用:

for(int i = 0; i < 5; i++)
{
    Console.Write($"Enter e values for index {(i+1)}:");
    z = int.Parse(Console.ReadLine());
    obj.array(i,z);
}           
obj.readarray();

当然,该代码中还有很多问题。从命名约定开始,继续存在索引超出范围的风险...... 我将把它留给 OP,只解决问题中的直接问题。

【讨论】:

    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2015-08-14
    • 2011-07-05
    • 2016-02-11
    • 2013-02-10
    • 2020-06-18
    相关资源
    最近更新 更多