This is part of a method inside of a class class. My goal is to generate a random number that number will be stored in a variable called iCell. After that, iCell will be used for the switch statement to change the character, cell. I am getting an error from the iCell = Random.Next(1,9); line that says "Error, An object reference is required for the non-static field, method, or property 'System.Random.Next(int, int)'". Is it not possible to have a random number generator in a class method?
public void CPUMove() //method marks cell for CPU
char cell;
int iCell;
Random rand = new Random();
iCell = Random.Next(1, 9);
switch (iCell)
{
case 1:
cell = '1';
break;
case 2:
cell = '2';
break;
case 3:
cell = '3';
break;
case 4:
cell = '4';
break;
case 5:
cell = '5';
break;
case 6:
cell = '6';
break;
case 7:
cell = '7';
break;
case 8:
cell = '8';
break;
case 9:
cell = '9';
break;
}
iCell = rand.Next(1, 9);
Use the object you already created.
Please note that you should create this Random instance once in your program. Maybe you can make it a class variable or even a static class variable.
You want rand.Next rather than Random.Next so that you're referencing the instance you just created
Also, you can get rid of that big switch statement. Just write:
cell = iCell.ToString()[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With