c# - 如何选择随机数数组的多个值
问题描述
我正在创建一个骰子程序来进一步学习。该程序将掷 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();
}
}
我目前正在打印出您选择的一个骰子值,但我不确定如何打印出多个选择。我能想到的唯一方法是输入所有选项。但这似乎不对,会使我的代码如此之长。
我在想某种循环可能会起作用?但我可以看到如何。
这是我第一次在这里发帖,所以希望我做得对。提前致谢!
解决方案
例如,您可以通过让他输入他选择的骰子来获得多个用户选择,用逗号分隔它们
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 块,然后如果没有抛出错误继续您的工作,否则重试输入选定值。
推荐阅读
- sql - 将数据从测试服务器上的大表复制到 SSIS 中生产服务器上的表
- javascript - 使用状态挂钩时 UI 中的图像不会更新
- php - 如何将 Dropzone 集成到我的联系表中以要求 3-5 张照片?
- css - 重叠按钮的 Z 索引不起作用
- python - 在 tkinter GUI 开发中更改对象检测代码功能
- video - 给定一个 mp4 列表,生成 fmp4 并连接
- flutter - 如何在颤动中显示每日通知?
- fonts - 是否可以生成仅垂直的字体?
- javascript - javascript类是否可以定义一个在调用类时触发的方法?
- deep-learning - 'ner_ontonotes_bert_mult' 模型自定义火车