如何从用户输入创建数组

时间:2014-09-12 17:45:40

标签: c# arrays for-loop scope

public class TEST
{
    static void Main(string[] args)
    {

        string Name = "";
        double Value = 0;
        Array test1 = new Array(Name, Value);

        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine("Enter A Customer:");
            Name = Console.ReadLine();
            Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
            Value = Convert.ToDouble(Console.ReadLine());
        }

        test1.Display();

        Console.ReadLine();
    }
}

所以在另一个类中,我有我的数组。它的设置方式是,它一次向一个数组添加一个用户,并在另一个数组中添加用户对应的数字。

我遇到问题的部分是主要编码。我提示用户输入并希望它调用我的其他类方法并一次向一个用户填充数组。但是,我被困住了。

我知道为什么上面的代码不起作用,因为对象调用只调用一次,因此初始值是保存的值。但是当我把新的数组(Name,Value);在for循环中它告诉我test1.Display();是一个未分配的变量。

有没有办法可以解决这个问题。我知道可能有另一种使用列表或其他东西的简单方法,但我还没有那么远。如果你能解释或暗示或任何事情,我会很感激。 :)

1 个答案:

答案 0 :(得分:0)

在这种情况下,最好使用List<T>

您必须创建一个类,然后您可以创建List<T>来保存项目:

public class Customer
{
  public string Name {get;set;}
  public double Value {get;set;}
}

和:

 static void Main(string[] args)
    {

        List<Customer> customers = new List<Customer>;

        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine("Enter A Customer:");
            Customer customer = new Customer(); // create new object
            customer.Name = Console.ReadLine();  // set name Property
            Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
            customer.Value = Convert.ToDouble(Console.ReadLine());// set Value Property
            customers.Add(customer); // add customer to List
        }


        Console.ReadLine();
    }
相关问题