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!
28 Minutes
Discussion Span
Related Article: java list
is a solved Java discussion thread by anisha.silva that has 1 reply, was last updated 3 months ago and has been tagged with the keywords: java, method, list.
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
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16