0

I have recently begun programming at university and I am a little stumped with one of my tutorial problems.

I basically need to create a method within a class which uses the Random.nextInt() method to flip a coin, assigning and saving the value once the process has been run.

MY current attempts include this:

public void Flip() {

int flipResult;

flipResult = mRandNumGen.nextInt(1);

if(flipResult == 0)
{
mFace = 'H';
}
else
{
mFace = 'T'
}

}

mFace and mRandNumGen are variables which have been declared already outside the specific method. What exactly is going wrong here? I can't for the life of me get this to work :/

2 Answers2

3

Simple way to do this:

if (mRandNumGen.nextBoolean()) {
    mFace = 'H';
} else {
    mFace = 'T';
}
2

The first argument in Random.nextInt is an exclusive upper bound, not inclusive. So with n=1 it will always return 0. for n=2 it will return either 0 or 1 which is what you're looking for.