【问题标题】:How do you realign array data in comparison to another array when the index is out of sync?当索引不同步时,如何与另一个数组相比重新对齐数组数据?
【发布时间】:2018-11-23 03:21:46
【问题描述】:

我创建了一个“选择您的案例”游戏,它使用包含所有奖金金额和用户可以选择的案例编号的现金奖励数组。当他们选择一个数字时,它会告诉用户他们的情况。但是,最后它会吐出所有案例以及每个案例中的内容,并且数据未对齐一个索引。

    static void Main(string[] args)
    {
        int[] cashPrizeArray = new int[26] { 0, 1, 2, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 15000, 20000, 25000, 50000, 75000, 100000, 200000 };
        int[] caseArray = new int[26] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
        Array.Sort(cashPrizeArray);

        Random rnd = new Random();
        int[] cashPrizeArrayR = cashPrizeArray.OrderBy(x => rnd.Next()).ToArray();
        foreach (int i in cashPrizeArrayR)
        {
            Console.Write("{0} ", i);
        }

        Console.WriteLine("\n(please ignore the numbers above)\n\n\nDeal or Not!");
        Console.Write("Choose a case: 1-26: ");
        int userCase = int.Parse(Console.ReadLine());

        if (!caseArray.Contains(userCase))
        {
            Console.WriteLine("\nUnexpected input text.\nThis application will now be terminated.\nPress ENTER to continue...");
            Console.ReadLine();
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("You chose case " + userCase);
            Console.ReadLine();
        }

        Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase]);
        Console.ReadLine();

        Console.WriteLine("\nFor reference, below are the case numbers and their values: ");
        Console.ReadLine();
        var caseAndPrize = cashPrizeArrayR.Zip(caseArray, (p, c) => new { Prize = p, Case = c });
        foreach (var pc in caseAndPrize)
        {
            Console.WriteLine("Case " + pc.Case + " $" + (pc.Prize));
        }
        Console.ReadLine();
    }

它运行良好,但输出值不正确,好像数据列向下移动一样。谁能提供我出错的解决方案?非常感谢。

【问题讨论】:

  • 索引从零开始
  • 您可能想研究使用类或结构,将值一起放入 one 数组中,那么您将不会有任何不同步的机会,因为您正在一起移动所有属于一起的数据。

标签: c# arrays if-statement indexing


【解决方案1】:

cashPrizeArrayR[userCase] 根据索引进行选择。您是否考虑过使用 KeyValuePair 或 Dictionary 来代替 int[]?

【讨论】:

    【解决方案2】:

    改变这一行:

    Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase]);
    

    到这里:

    Console.WriteLine("This case contains...\n$" + cashPrizeArrayR[userCase - 1]);
    

    进一步的建议

    替换这个:

    int userCase = int.Parse(Console.ReadLine());
    

    bool validKey = int.TryParse(Console.ReadLine(), out var userCase);
    
    if (!validKey|| !caseArray.Contains(userCase))
    { 
        // <snipped>
    

    【讨论】:

    • 索引是从零开始的,所以你需要考虑到这一点。
    • 你也应该加强这一行:int userCase = int.Parse(Console.ReadLine()); 因为如果用户只是按下回车键就会抛出异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2011-05-17
    • 2018-05-23
    • 2016-06-20
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多