开发者

Arrays in C# getting user input and passing to a different class

I am working on a project, Yes its for school. I'm having a hard time understanding how to pass the user input and store it with a array. The project is to get high and low temps for seven days and store in different arrays then compute the ave high etc. how do I collect the input and store it in a array in a different class? I think I almost have it but not sure where I'm going wrong

I have this so far but get a error:

Cannot implicitly convert type 'int' to 'int[]'

na开发者_JS百科mespace Project_Console_3
{
    class Program
    {
        static void Main(string[] args)
        {
            WeeklyTemperature Temp = new WeeklyTemperature();

            int Count = 0;
            while (Count < 7)
            {
                Console.WriteLine("Enter The High Temperature for Day {0}", Count+1); 
                Temp.HTemp1 =Console.ReadLine();      // save the number as a string number
                Temp.HTemp = Convert.ToInt32(Temp.HTemp1); // change the string number to a integer as HTemp
                Console.WriteLine("--------------------------------");//Draws a line

                Console.WriteLine("Enter The Low Temperature for Day {0}", Count+1); 
                Temp.LTemp1 =Console.ReadLine();      // save the number as a string number
                Temp.LTemp = Convert.ToInt32(Temp.LTemp1);
                Console.WriteLine("--------------------------------");//Draws a line
                Count = Count + 1;
                Console.Clear();
            }       
        }
    }
}

WeeklyTemperature.cs

namespace Project_Console_3
{
    class WeeklyTemperature
    {
        public int[] HTemp = new int[7];
        public int[] LTemp = new int[7];
        public string HTemp1;
        public string LTemp1;
    }
}


It looks like all you need to do is change this line:

Temp.HTemp = Convert.ToInt32(Temp.HTemp1);

to

Temp.HTemp[Count] = Convert.ToInt32(Temp.HTemp1)


Your error message tells you that you have a mismatch in the assignment of variables. in this line:

Temp.HTemp = Convert.ToInt32(Temp.HTemp1); 

The return value is of type int but the variable Temp.HTemp is of type int[] which is an array that holds individual integer. To store values in an array the compiler has to know at which position it has to put the value.

Indexing an array works with the [] operators:

int pos = 0;
Temp.HTemp[pos] = 5;

will store a 5 on the first position.

Since you have a counting variable in your while loop you can use it to index the position where the numbers should be stored, as Jim Ross already showed in his answer.

More on the topic of indexing you can find here, and a tutorial is here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜