Tuesday, February 16, 2021

Get specific length random number in Java

Get specific length random number in Java:

import java.util.Random; 

public class RandomJavaProgram {
   public static void main(String []args) {
       RandomNumber RandomNumberObj = new RandomNumber();
       System.out.println(RandomNumberObj.getRandomNumber(3));
   }
}

class RandomNumber {
    public String getRandomNumber(int digitLength) {
        int[] numberContainer = new int[digitLength];
        String mainRandomNumber = "";
        Random rand = new Random();

        for ( int i = 0; i < digitLength; i++ ) {
            numberContainer[i] = rand.nextInt(10);
        }        

        for ( int j = 0; j < digitLength; j++ ) {
            mainRandomNumber = mainRandomNumber + String.valueOf(numberContainer[j]);
        }       

        return mainRandomNumber;
    }
}

No comments:

Post a Comment

Suomen kieli (Imperfekti)

In Finnish, the imperfekti is the past tense that describes actions that happened in the past, like the English simple past (e.g., "I ...