這裏的學生。根據用戶輸入尋找數組中的最大值(C#)
目前正在一個項目中尋找基於用戶輸入的數組中的最高值。
我正在使用的當前foreach循環獲取用戶輸入,然後只找到匹配第二個數組的第一個實例,而不是繼續循環。
我試過兩種方法。兩者都以相同的結果結束。
首先,我嘗試創建一個列表,然後排序和反轉。這樣我可以拿0指數,它是最高
static void Main(string[] args)
{
string[] fishColors = new string[15] { "pink", "purple", "red", "orange", "blue", "green", "pink", "green", "blue", "red", "orange", "purple", "green", "red", "purple" };
int[] fishLengths = new int[15] { 49, 5, 45, 10, 14, 1, 44, 17, 48, 11, 13, 17, 20, 15, 37 };
List<int> userFishLengths = new List<int>();
int userChoice = 0;
string input = null;
int longestFish = 0;
do {
Console.WriteLine("Please select the number from the list below for the color of fish you would like to choose:\r\n0. Pink\r\n1. Purple\r\n2. Red\r\n3. Orange\r\n4. Blue\r\n5. Green");
input = Console.ReadLine();
} while (Int32.TryParse(input, out userChoice) == false) ;
string userColor = fishColors[userChoice];
foreach (string fish in fishColors)
{
if (userColor == fish)
{
int indexID = Array.IndexOf(fishColors, fish);
int fishLength = fishLengths[indexID];
userFishLengths.Add(fishLength);
}
}
userFishLengths.Sort();
userFishLengths.Reverse();
Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + userFishLengths[0]+" inches.");
}
其次,我試圖創建一個值,它需要每次都在,並覆蓋變量,如果是較大的。
static void Main(string[] args)
{
string[] fishColors = new string[15] { "pink", "purple", "red", "orange", "blue", "green", "pink", "green", "blue", "red", "orange", "purple", "green", "red", "purple" };
int[] fishLengths = new int[15] { 49, 5, 45, 10, 14, 1, 44, 17, 48, 11, 13, 17, 20, 15, 37 };
int userChoice = 0;
string input = null;
int longestFish = 0;
do {
Console.WriteLine("Please select the number from the list below for the color of fish you would like to choose:\r\n0. Pink\r\n1. Purple\r\n2. Red\r\n3. Orange\r\n4. Blue\r\n5. Green");
input = Console.ReadLine();
} while (Int32.TryParse(input, out userChoice) == false) ;
string userColor = fishColors[userChoice];
foreach (string fish in fishColors)
{
if (userColor == fish)
{
int indexID = Array.IndexOf(fishColors, fish);
int fishLength = fishLengths[indexID];
if (fishLength > longestFish)
{
longestFish = fishLength;
}
}
}
Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + longestFish + " inches.");
}
任何幫助/建議,將不勝感激。謝謝!
問題是什麼時,用戶應該選擇一種顏色,程序,長度響應? –
正確,程序以用戶所選顏色的最大長度進行響應。 –
好的,我會和Daniel Mays一起回答。如果你需要顏色作爲一個唯一的標識符,那麼將它們作爲關鍵字的字典和它們對應的長度數組作爲值將是最好的方法。 –