Home > Software design >  How to choose either char 'A' or 'B' by using random() in C#
How to choose either char 'A' or 'B' by using random() in C#

Time:08-31

I'm creating a board game that a computer can choose either 'A' or 'B'. I used Random() as below. However, the 'tempChar' shows numeric numbers like '86' and '79' which aren't what I expected.

I'd like to know what I need to change to make a computer select only 'A' or 'B'.

public class ComputerPlayer: Player
{
    Random rndm = new Random();
    public new char inputSymbol()
    {
        char tempChar = (char)rndm.Next('A', 'B');
        return tempChar;
        
    }

}

CodePudding user response:

char is implicitly convertible to an int, that's what happens here.

You could use this approach:

private static readonly Random rndm = new Random();
private static readonly char[] inputOptions = { 'A', 'B' };

public new char inputSymbol()
{
    return inputOptions[rndm.Next(0, inputOptions.Length)];
}

By the way, you can omit the first parameter in Random.Next if it's 0:

return inputOptions[rndm.Next(inputOptions.Length)];

CodePudding user response:

Next method had parameters as next(int,int) so it treats "A" and "B" as ascii values. For this what you can do is get random from 2 int values and use if else statement to get "A" or "B".

if(1 == rndm.next(1,3))
    return "A"
else
    return "B"

CodePudding user response:

public class ComputerPlayer: Player
{
    Random rndm = new Random();

    public new char inputSymbol()
    {
        char[] tempChar = { 'A', 'B' };

        var rndmNumber = rndm.Next(0, 2);

        return tempChar[rndmNumber};        
    }
}
  • Related