0

Hi guys just carrying on working on my first app, done mainly to learn and nothing else. I want the user to be able to type in 2d6+4 OR 2d6, you should be able to substitute those numbers for any number. I'm getting errors parsing the information and I think it has something to do with the array containing more or less values than I anticipated, or it for some reason left the delimiter in. typing 2d6+4 or 2d6 +4 works fine, 2d6 however does not, which is what I thought the if statement should guard against. Any ideas?

        Console.WriteLine("Please type the roll you would like to perform, for example - 2d6+4");
        var rollLine = Console.ReadLine();
        var diceLine = rollLine.Split(new Char[] { 'd', '+' }, StringSplitOptions.RemoveEmptyEntries);
        diceCount = int.Parse(diceLine[0]);
        diceType = int.Parse(diceLine[1]);
        if (rollLine.Length > 2)
        {
        bonus = int.Parse(diceLine[2]);
        }
        else
        {
            bonus = 0;
        }

3 Answers 3

2

It looks like you are just using the wrong variable for the length comparison. You are comparing the length of the string, not the length of the split array. It should be:

if (diceLine.Length > 2)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it was just using the wrong variable. It was the array length I wanted to check for some reason I thought rollLine was the array after parsing when its plainly clear its not. Thank you!
1

When user entered "2d6", the string length is 3, i.e. following rule is true

if (rollLine.Length > 2)

However, as per your logic you will get array of 2 items in the diceLine, i.e. diceLine[0] and diceLine[1] but after condition with length you call diceLine[2] that does not exist.

I.e. either change condition to

if (rollLine.Length == 5) // 2d6+4

or check for the length of the array

if (diceLine.Length > 2) 

2 Comments

It's probably preferable to check the length of the array as in this example in case you want to do 2d12 etc. at some point.
dice is 1 to 6, but I agree it depends on the need
0

You want your IF to check if the rollLine length is greater than 3, not 2. As the smallest thing you'll type in is, for example, 2d6, you want to check for the bonus only when the rollLine is more than 3 characters.

if (rollLine.Length > 3)
{
    bonus = int.Parse(diceLine[2]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.