We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,434 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Index number in Linked List with List Iterator

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

ect.
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.io.IOException;
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(System.in);
        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));
            Collections.sort(list);
            System.out.print(list + "\n");

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

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

2
Contributors
1
Reply
28 Minutes
Discussion Span
1 Year Ago
Last Updated
2
Views
sonicx2218
Junior Poster in Training
65 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0548 seconds using 2.66MB