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.
Question
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;
}
Solution
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.
OTHER TIPS
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];
In addition to other answers: better off making the Random instance static.
class MyClass {
static Random rand = new Random();
public void CPUMove() { //method marks cell for CPU
char cell;
int iCell;
iCell = rand.Next(1, 9);
cell = iCell.ToString()[0];
}
}
You can do it like that:
// Simplest case, not thread safe
// The same generator for all CPUMove() calls
private static Random rand = new Random();
// method marks cell for CPU
public void CPUMove() {
// Don't re-create Random each time you need a random value:
// the values generated will be badly skewed
// Random rand = new Random();
// You don't need any switch/case here, just a conversion
Char cell = (Char) (rand.Next('1', '9'));
...
}