这里的学生。根据用户输入寻找数组中的最大值(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一起回答。如果你需要颜色作为一个唯一的标识符,那么将它们作为关键字的字典和它们对应的长度数组作为值将是最好的方法。 –