Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generator in a class method

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;
    }
like image 947
user3471066 Avatar asked Aug 13 '26 21:08

user3471066


2 Answers

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.

like image 80
nvoigt Avatar answered Aug 16 '26 11:08

nvoigt


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];
like image 21
Ben Aaronson Avatar answered Aug 16 '26 10:08

Ben Aaronson