c# - 更改if语句中的字符串是不行的

时间:2015-11-03 00:19:10

标签: c# string if-statement

我在游戏命令中有这个,所以这里是

internal class GambleCommand : Command
{
    public GambleCommand() : base("roll", 3)
    {
    }

    protected override bool Process(Player player, RealmTime time, string[] args)
    {
        try
        {
            if (args.Length == 1)
            {

                int num = int.Parse(args[0]);
                Random rnd = new Random();
                string pl = player.Name;
                string rand = rnd.Next(0, num).ToString();

                if (num < 0)
                {
                    rand = rnd.Next(num, 0).ToString();
                }

                foreach (Client i in player.Manager.Clients.Values)
                {
                    i.SendPacket(new TextPacket
                    {
                        BubbleTime = 0,
                        Stars = -1,
                        Name = pl,
                        Text = "rolled a " + rand + " out of " + num + "."
                    });
                }
            }
        }
        catch
        {
            Random rnd = new Random();
            string pl = player.Name;
            string rand = rnd.Next(0, 100).ToString();
            foreach (Client i in player.Manager.Clients.Values)
            {
                i.SendPacket(new TextPacket
                {
                    BubbleTime = 0,
                    Stars = -1,
                    Name = pl,
                    Text = "rolled a " + rand
                });
            }
        }
        return true;
    }
}

除了

部分之外,这里的一切都很好
if (num < 0)
{
    rand = rnd.Next(num, 0).ToString();
}

基本上应该做的是将(0,num)num的最大数量更改为(num,0),如果您选择的数字为负数。现在,当我把它放到负数时,它会转到默认的0-100,即catch语句。

3 个答案:

答案 0 :(得分:2)

rnd.next采用最小值,后跟最大值。

int num = int.Parse(args[0]);
Random rnd = new Random();
string pl = player.Name;
string rand = rnd.Next(0, num).ToString();//Exception since negative value is less than 0
if (num < 0)
{
    rand = rnd.Next(num, 0).ToString();
}

试试这个:

string rand = "";
if(num < 0)rand = rnd.Next(num, 0).ToString();
else rand = rnd.Next(0, num).ToString();

答案 1 :(得分:0)

当num值为负数时,您必须在下面的行中获得异常:

 string rand = rnd.Next(0, num).ToString();

enter image description here

如果阻止,则在上面移动语句:

if (num < 0) string rand = rnd.Next(num, 0).ToString();

答案 2 :(得分:-1)

还有一点需要注意:这一行...

 Text = "rolled a " + rand + " out of " + num + "." 

num需要为num.ToString()+&#34;。&#34;