我们如何在C#中显示整数类型数组的元素

时间:2013-02-10 04:46:00

标签: c#

我声明一个int类型数组并尝试打印所有元素,但它只打印最后一个元素.....给我正确的代码.....

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int[] arr;
        int range;

        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            range = Convert.ToInt32(textBox1.Text);
            arr = new int[range];


        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < range; i++)
            {
                arr[i] = Convert.ToInt32(textBox2.Text);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            for(int i =0;i<range;i++)
            {
                textBox3.Text = textBox3.Text + arr[i].ToString();

            }
        }
   }
}

5 个答案:

答案 0 :(得分:1)

这一行:arr[i] = Convert.ToInt32(textBox2.Text);会将数组中的每个元素设置为textbox2中的值。这是你的意图吗?

答案 1 :(得分:0)

Int数组很常见。它们存储许多整数值。这些值可以在很多方面使用。这个介绍性材料涵盖了int数组,显示了声明,赋值,元素,循环和方法。请参阅here

此代码是工作数组int的简单示例

using System;

class Program
{
    static void Main()
    {
    int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
    int[] arr2 = { 3, 4, 5 };           // Another
    var arr3 = new int[] { 3, 4, 5 };   // Another

    int[] arr4 = new int[3];            // Declare int array of zeros
    arr4[0] = 3;
    arr4[1] = 4;
    arr4[2] = 5;

    if (arr1[0] == arr2[0] &&
        arr1[0] == arr3[0] &&
        arr1[0] == arr4[0])
    {
        Console.WriteLine("First elements are the same");
    }
    }
}

using System;

class Program
{
    static void Main()
    {
    // Loop over array of integers.
    foreach (int id in GetEmployeeIds())
    {
        Console.WriteLine(id);
    }
    // Loop over array of integers.
    int[] employees = GetEmployeeIds();
    for (int i = 0; i < employees.Length; i++)
    {
        Console.WriteLine(employees[i]);
    }
    }

    /// <summary>
    /// Returns an array of integers.
    /// </summary>
    static int[] GetEmployeeIds()
    {
    int[] employees = new int[5];
    employees[0] = 1;
    employees[1] = 3;
    employees[2] = 5;
    employees[3] = 7;
    employees[4] = 8;
    return employees;
    }
}

Output

1
3
5
7
8
1
3
5
7
8

答案 2 :(得分:0)

textBox2.Text是一个数字还是一系列数字?例如,如果它是1,2,3那么你必须Split ,上的字符串,然后将String[]的每个条目转换回整数,并将它们存储在数组中。

答案 3 :(得分:0)

我不确定你要做什么。

无论何时更改,您都会从文本框中读取输入 并将该数组重新创建为该文本框中指示的大小。

第二个文本框在数组被更改为第二个时填充数组 textbox接受为输入(这根本没有意义)。

button1将数组显示为字符串,这可能没问题。

您可能希望将第二个文本框更改为填充数组的按钮。

否则,重新考虑你的第二个文本框的意图,这是没有意义的。

答案 4 :(得分:0)

你在哪里清楚textBox3.Text?

您正在此文本框中累积。当你这样做,输入溢出时,你只会看到最后添加的东西。也许这就是问题所在。我可能会调整:

private void button1_Click(object sender, EventArgs e)
{
    textBox3.Text = "";

    for(int i =0;i<range;i++)
    {
        textBox3.Text = textBox3.Text + arr[i].ToString();

    }
}