skip to Main Content

I have a random dice generator with 2 dice. I’m using a compare statement to check the random result of the two dice and re roll if they are the same. here is the code to roll one of the dice

void Roll1() {
    setState(() {
      oneDiceNumber = Random().nextInt(6) + 1;
  if (oneDiceNumber == twoDiceNumber) {
        oneDiceNumber = Random().nextInt(6) + 1;
        twoDiceNumber = Random().nextInt(6) + 1;
      }
    });
  }

what I want the code to do is loop the if statement until it gets a result that isn’t a tie.

thanks so much

2

Answers


  1. Try a while loop

    oneDiceNumber = 0;
    twoDiceNumber = 0;
    
    while(oneDiceNumber == twoDiceNumber){
       oneDiceNumber = Random().nextInt(6) + 1;
        twoDiceNumber = Random().nextInt(6) + 1;
    }
    
    Login or Signup to reply.
  2. You could also do this using recursion:
    Define a function called getRandomDice():

    getRandomDice() {
       int oneDiceNumber = Random().nextInt(6) + 1;
       int twoDiceNumber = Random().nextInt(6) + 1;
       if (oneDiceNumber == twoDiceNumber) {
           return getRandomDice();
       } else {
           return [oneDiceNumber, twoDiceNumber];
       }
    }
    

    and you could call this using in your function like this:

    List<int> values = getRandomDice();
    int firstNum = values[0];
    int secondNum = values[1];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search