简体   繁体   中英

Scala Random Number

Ok, I understand how to implement a random number generator in Scala and how to set the upper bound for the random number being generated, but I am confused as how to change the lower bound. For example:

    var computerGuess= scala.util.Random
    var higher=100
    var computerGuessInt=computerGuess.nextInt(higher)

will let the computer generate a random number from 0 to 100.

But I want to change the lower bound to be, say 29 so that the computer could pick a random number from 29 to 100. How can I do this?

Without getting into language specific solutions (scala may have an API for generating a number with a lower bound) - you could always create your own lower bound by adding it to the number generated .

This means that to generate a number from 29 to 100, you can generate a number from 0 to 71, and add 29 to it:

var computerGuess = scala.util.Random
var higher = 100
var lower = 29
var computerGuessInt = computerGuess.nextInt(higher - lower) + lower

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM