How to Generate 6 Digit Random Number Scala?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in Scala.

Here’s how to generate a 6-digit random number in Scala.

Using `scala.util.Random` and string manipulation.

object RandomNumberGenerator {

def generateSixDigitNumber(): String = {
// Create a Random object
val random = scala.util.Random

// Generate a random integer between 100000 and 999999 (inclusive)
val randomNumber = random.nextInt(900000) + 100000

// Convert the integer to a string
val stringNumber = randomNumber.toString

// Ensure the string has 6 digits by prepending leading zeros if necessary
val paddedNumber = stringNumber.padTo(6, '0')
paddedNumber
}

def main(args: Array[String]): Unit = {
val number = generateSixDigitNumber()
println(s"Generated 6-digit number: $number")
}
}

Explanation:-

1. The `generateSixDigitNumber` function creates a `scala.util.Random` object.
2. It uses `random.nextInt(upperBound)` to generate a random integer between 0 (inclusive) and `upperBound` (exclusive). In this case, we set `upperBound` to 900000 to ensure the range falls within numbers less than 1 million.
3. To guarantee a 6-digit number, it adds 100000 to the generated random number, shifting the range from 0 to 999999 to 100000 to 999999 (inclusive).
4. It converts the integer to a string using `toString`.
5. It uses `padTo(6, ‘0’)` to pad the string with leading zeros if necessary to reach a length of 6.