2010-11-03 46 views
-1

我正在研究一個項目,是它的學校。我很難理解如何傳遞用戶輸入並將其與數組一起存儲。該項目將獲得七天的高溫和低溫,並存儲在不同的陣列中,然後計算出高溫等。我如何收集輸入並將其存儲在不同類的數組中?我想,我幾乎有它,但不知道我要去哪裏錯了C#中的數組獲取用戶輸入並傳遞給不同的類

我有這個迄今爲止卻得到了一個錯誤:

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

namespace 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; 
    } 
} 
+0

我柯克的路線質疑(你能改寫這個問題來證明你嘗試過什麼?),但與此同時,一個一般原則同意可能會考慮一個Windows窗體,一個Web窗體,或者簡單地接受來自控制檯的用戶輸入。所有這些在Visual Studio中都非常簡單。祝你好運。 – LesterDove 2010-11-03 03:37:09

+0

,我想你應該把問題標記爲「家庭作業」 – LesterDove 2010-11-03 03:39:32

回答

1

它看起來像所有你需要做的是改變這條線:

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

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

您的錯誤消息告訴您,您在變量賦值中存在不匹配。 在這一行:

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

返回值是int類型,但所述可變Temp.HTempint[],其類型是保持各個整數的陣列組成。 要將值存儲在數組中,編譯器必須知道它必須在哪個位置放置該值。

索引的陣列與所述運營商[]作品:

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

將5存儲在第一位置。

由於您的while循環中有一個計數變量,因此您可以使用它來爲數字應存儲的位置編制索引,正如Jim Ross在他的答案中已經顯示的那樣。

更多索引的話題,你可以找到here和教程here