C# 中的骰子控制台应用程序 returns 错误

Dice roll console app returns errors in C#

我正在尝试编写一个控制台应用程序,它可以使用多种类型的骰子来掷骰子,并在完成之后要求用户确认新掷骰或退出。

这是显示问题的最小部分:

string rolltype = "bob";
if (rolltype = "d4") // <-- error on this line
{
    Console.WriteLine("d4 roll is {0}", d4);
}

代码在编译时产生以下错误:

cannot implicitly convert type string to bool

完整来源:

namespace diceroll
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int d4 = rand.Next(1, 5);
            int d6 = rand.Next(1, 7);
            int d8 = rand.Next(1, 9);
            int d10 = rand.Next(1, 11);
            int d12 = rand.Next(1, 13);
            int d20 = rand.Next(1, 21);
            string rolltype;
            Console.WriteLine("what do you want to roll?");
            rolltype = (Console.ReadLine());
            Console.WriteLine("your choice is {0}", rolltype);
            if (rolltype = "d4")
            {
                Console.WriteLine("d4 roll is {0}", d4);
            }
            else { }
            Console.ReadKey();
        }
    }
}

我希望在这里实现的是控制台询问滚动类型,并在得到它后,它 returns 你一个随机数。 (rolltype = "d4" ) returns 错误 "cannot implicitly convert type string to bool"。

 if (rolltype == "d4")

您需要使用相等运算符而不是赋值运算符。

"cannot implicitly convert type string to bool", and i have no idea how to fix it

这是因为下面的代码不会产生布尔值,下面您试图将 rolltype 分配给字符串 "d4" 因此出现错误。

if (rolltype = "d4")

你要的是这个:

if (rolltype == "d4")

Also is there a more elegant way of going at this than writing 6 separate if statements for the rolltypes?

当然,我们可以使用一个数组来存储可能的选项,然后循环遍历它。

第 1 步 - 创建数组:

string[] myArray = {"d4","d6","d8","d10","d12","d20"};

现在你的代码变成这样:

Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};

第 2 步 - 遍历它以查找输入的值是否等于数组中的任何值。

foreach(string str in myArray){
   if (rolltype == str){
      // do something
      break; // if we get here then we don't need to loop any further
   }
}

现在你的代码变成这样:

Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};
string rolltype;
Console.WriteLine("what do you want to roll?");
rolltype = (Console.ReadLine());
Console.WriteLine("your choice is {0}", rolltype);

foreach(string str in myArray){
    if (rolltype == str){
          // do something
        break; // if we get here then we don't need to loop any further
    }
}

Chris 在评论中建议的另一个好的解决方案是简单地从字符串中取出数字。这显然会减少您目前拥有的 rand.Next() 数量。

示例:

int dieType = int.Parse(rollType.Substring(1)); 
int result = rand.Next(1,dieType+1);