Search code examples
javarandomlinked-listsingly-linked-list

Adding a random number into my singly linked list, but it always adds the same randomized number


I'm making a singly linked list, and the numbers I am adding into the list need to be random. I can't seem to get a randomized number every time, it instead prints the same randomized number 10 times when I need it to be different random numbers.

I understand this is happening because the random number is only assigned once, but how do I make it change every time?

    //Creating a random number between 1 and 107
    static Random rnum = new Random();
    static int randomNumber = rnum.nextInt((107- 1) + 1);
    
    public static void main(String[] args) {

        //Producer List
        SinglyLinkedList pList = new SinglyLinkedList();
        
        // Add random nodes to the list 
        for (int i = 0; i < 10; i++) {
            pList.addNode(randomNumber);
        }

The output of the code would be "71 71 71 71 71 (repeated)" and I just want to figure out how to make it a different number every time! Please help!


Solution

  • Instead of storing one randomly generated number, you should generate a new random number for each iteration in your loop. It's also a good idea to seed the Random object with the current time

    static Random rnum = new Random(System.currentTimeMillis());
    //static int randomNumber = rnum.nextInt((107- 1) + 1);
    
    public static void main(String[] args) {
    
        //Producer List
        SinglyLinkedList pList = new SinglyLinkedList();
        
        // Add random nodes to the list 
        for (int i = 0; i < 10; i++) {
            pList.addNode((rNum.nextInt(106) + 1));
        }