Home > Blockchain >  Writing a 'for loop' for random no which is not zero(0) but still I'm getting zero(0)
Writing a 'for loop' for random no which is not zero(0) but still I'm getting zero(0)

Time:11-23

I'm new to dart, and I'm writing the following for loop for random num which is not a zero, but it still returns zero to me:

  int Num = 1;
  for (var i = 1; i != 0 && i <= 6; i  ) {
    final _random = Random();
    Num = _random.nextInt(i);
  }
  print('Randon num is $Num');

CodePudding user response:

A good place for problems like this is the dart api. This link provides you with everything you need.

Here it says the following:

nextInt(int max) → int Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive. [...] Also i represents the max value the nextInt() method will produce.

To generate a single random number:

import 'dart:math';

void main() {
  int maxNb = 10; 
  
  generateRandomNumber(int maxNb) {
    final int number = Random().nextInt(maxNb)   1; 
    return number;
  }
  
  int result = generateRandomNumber(maxNb);
  print(result);
}

To generate multiple random numbers:

import 'dart:math';

void main() {
  int maxNb = 10;
  int amount = 6;
  List randomNumbers = [];
  
  generateRandomNumbers(int amount, int maxNb) {
    for (var i = 1; i <= amount; i  ) {
    final number = Random().nextInt(maxNb)   1;
    randomNumbers.add(number);
    } 
  }
  generateRandomNumbers(amount,maxNb);
  print(randomNumbers);
}

FYI: Variable names are NOT capitalized.

CodePudding user response:

Your random number can be zero because you want a random number between 0 and i, so 0 is in your range , if you want a random number that doesn't include zero in the range you can use a method like this:

int nextRangeInt(int min, int max) => min   Random().nextInt((max   1) - min);

in your case :

int Num = 1;
for (var i = 1; i <= 6; i  )
{
Num = nextRangeInt(1,i);
}
print('Randon num is $Num')

CodePudding user response:

You can use like;

 
var Num;

 for (var i=1; i <= 6; i  ) {
    Num = Random().nextInt(i)  1;
    print('Random num is $Num');
 }
  

  • Related