根据用户输入(C#)查找数组中的最高值

时间:2017-09-03 18:28:18

标签: c# arrays

学生在这里。

目前正在开发一个项目,以根据用户输入找到数组中的最高值。

我正在使用的当前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.");

    }

任何帮助/建议将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

问题出在Array.IndexOf()来电。

int indexID = Array.IndexOf(fishColors, fish);

fishColors数组的内容不是唯一的,因此Array.IndexOf(fishColors, fish)调用只是返回第一个匹配元素的索引。 (例如"pink" = 0"red" = 2

您最好使用不同的数据结构来存储这些值。考虑使用Dictionary<TKey,TValue>,例如

var fish = new Dictionary<string, int[]>()
{
    { "pink", new[] { 49, 44 } },
    { "purple", new[] { 5, 17, 37 } }
};

这样可以更方便地查找与颜色相关的长度。

或者,如果您必须保留两个数组的使用,则可以使用简单的for循环而不是foreach来执行此操作。

for (int i = 0; i < fishColors.Length; i++)
{
    if (userColor == fishColors[i])
    {
        int fishLength = fishLengths[i];

        if (fishLength > longestFish)
        {
            longestFish = fishLength;
        }
    }
}

答案 1 :(得分:0)

您的脚本无效,因为您使用:

int indexID = Array.IndexOf(fishColors, fish);

总是给你第一场比赛而不是当前的比赛。

实施例: 您搜索“紫色”并始终获得条目5。

如果我不想更改你的代码,那么这将改变版本:

        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];

            int indexID = 0;
            foreach (string fish in fishColors)
            {
                if (userColor == fish)
                {
                    int fishLength = fishLengths[indexID];

                    if (fishLength > longestFish)
                    {
                        longestFish = fishLength;
                    }
                }
                indexID++;
            }

            Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + longestFish + " inches.");
            Console.ReadKey();
        }

但是使用LINQ可以让它变得更简单:

        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];
            longestFish = fishColors
                .Zip(fishLengths, (color, length) => new { color, length })
                .Where(s => s.color.Equals(userColor)).Max(x => x.length);

            Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + longestFish + " inches.");
            Console.ReadKey();
        }

答案 2 :(得分:0)

我知道,这是学生项目;但问题是, Linq 是为

设计的
  string[] fishColors = new string[] //DONE: you have no need in specifing magic number "15"
    { "pink", "purple", "red", "orange", "blue", "green", "pink", "green", "blue", 
      "red", "orange", "purple", "green", "red", "purple" };

  int[] fishLengths = new int[] //DONE: you have no need in specifing magic number "15"
    { 49, 5, 45, 10, 14, 1, 44, 17, 48, 11, 13, 17, 20, 15, 37 };

  // Color/its index correspondence:
  //   Key - index: 1, 2, 3, ...
  // Value - color: pink, purple, red, ... 
  var colors = fishColors
    .Distinct()
    .Select((color, index) => new {
      color = color,
      index = index + 1, })
    .ToDictionary(item => item.index, item => item.color);

  string userColor = null;

  while (true) {
    Console.WriteLine("Please select the number from the list below for the color of fish you would like to choose:");

    //DONE: instead of hardcoding, build the string 
    Console.WriteLine(string.Join(Environment.NewLine, colors
      .OrderBy(pair => pair.Key)
      .Select(pair => $"{pair.Key}. {pair.Value}")));

    //DONE: input is valid if and only iff it's integer and it corresponds to color
    if (int.TryParse(Console.ReadLine(), out var code) && // <- out var - C# 7.0 Syntax
        colors.TryGetValue(code, out userColor))
      break;
  }

  //DONE: zip colors and lengths, filter out userColor fish only, get maximum 
  var result = fishColors
    .Zip(fishLengths, (color, length) => new { color = color, length = length })
    .Where(item => item.color == userColor)
    .Max(item => item.length);

  //DONE: do not concat string, but use string interpolation (or formatting)
  Console.WriteLine($"The longest fish in the tank with the color you chose ({userColor}) is {result} inches.");