首页 > 解决方案 > 如何选择随机数数组的多个值

问题描述

我正在创建一个骰子程序来进一步学习。该程序将掷 5 个骰子并将随机数值分配给 5 的数组并打印出这些值。之后,我希望玩家选择他或她想要保留的骰子,显示这些值,然后我将创建一个方法来滚动剩余的骰子。

我在选择多个骰子部分时遇到问题。

这是我到目前为止所拥有的:

    using System;


class HelloWorld {

  static void Main() {

    Random random = new Random();

    int[] diceEach = new int[5];


    int diceCount = 1;

    for(int i = 0; i < 5; i++)
    {
        diceEach[i] = random.Next(1, 7);
        Console.WriteLine("Dice " + diceCount +": " + diceEach[i]);
        diceCount++;
    }
    Console.WriteLine("To roll again hit R");

    Console.WriteLine("Please type the dice numbers that you would like to keep...");
    string diceKept = Console.ReadLine();

        if(diceKept == "1")
        {
            Console.Write(diceEach[0]);
        }

        else if(diceKept == "1")
        {
            Console.WriteLine(diceEach[1]);
        }

        else if(diceKept == "3")
        {
            Console.WriteLine(diceEach[2]);
        }

        else if(diceKept == "4")
        {
            Console.WriteLine(diceEach[3]);
        }

        else if(diceKept == "5")
        {
            Console.WriteLine(diceEach[4]);
        }

        else if(diceKept == "r")
        {
            Console.WriteLine("You have chosen to roll again");
        }


    Console.ReadLine();

  }

}

我目前正在打印出您选择的一个骰子值,但我不确定如何打印出多个选择。我能想到的唯一方法是输入所有选项。但这似乎不对,会使我的代码如此之长。

我在想某种循环可能会起作用?但我可以看到如何。

这是我第一次在这里发帖,所以希望我做得对。提前致谢!

标签: c#arraysrandomdice

解决方案


例如,您可以通过让他输入他选择的骰子来获得多个用户选择,用逗号分隔它们

1,2,5

然后展开代码

string diceKept = Console.ReadLine();

try{
    int[] selectedDices = diceKept.Split(',').Select(x => int.Parse(x)).ToArray();
}catch{
//invalid input - string value could not be parsed to int value.
}

您可以在函数中使用 try-catch 块,然后如果没有抛出错误继续您的工作,否则重试输入选定值。


推荐阅读