Start New Discussion within our Software Development Community

Hey bros. I made a program that prints out random numbers in a linked list. I want to have the index number next to each of the random numbers in the list. I guess for example like:
1 25
2 123
3 56

Here's m program so far, and it only sorts and prints out the list, but doesn't have an index next to each random integer. I think you use a list iterator to do this, but I can't figure it out... my output right now is like [23 58 129] but I kinda of want it to be like the list I made above.
Here's the code.

import java.util.*;
import java.util.Scanner;
import java.util.Random;

public class LinkedListProgram
    public static void main(String[] args) throws IOException
        int i,number, ran;
        Scanner sc = new Scanner(;
        LinkedList<Integer> list = new LinkedList<Integer>();
        ListIterator li;
        String line;
        Random random = new Random();
        int pick = random.nextInt(150);
        System.out.println("Enter # of nodes");
        number = sc.nextInt();
        if (number > 0)
            for (i = 0; i < number; i++)
            list.add(1+ (int)(Math.random()*150));
            System.out.print(list + "\n");

                System.out.println("\nnumber is less than 0\n");

Any helps is SUUUUPER APRECIATED. Thanks so much for all your times!

You will have to write a loop to get each element from the list one by one so you can print its value with its position in the list.

This article has been dead for over six months. Start a new discussion instead.