-1

I am a student, and i'm stuck here. I'm supposed to create multiple linked lists, the number of which is determined by user's entry. I thought of using a while loop, but i'm not sure how to name the lists differently like that. Help is appreciated.

    counter = 0;

    while (counter < userEntry){
    LinkedList <String> list (counter +1) = new LinkedList <String> ();
    counter++
    }

2 Answers2

0

There are few syntax errors in your code.

  • First the counter did not have a data type.
  • userEntry variable is not defined.
  • no semicolon at counter++

So, I editted your code snippet. Is this what you needed to do?

public static void main(String[] args) {
    int counter = 0;
    int userEntry = 4;

    while (counter < userEntry){
       LinkedList <String> list = new LinkedList<String> ();
       counter++;
    }
}

But as you are trying to create multiple linked lists, one option is to create an array of linked lists.

public static void main(String[] args) {
    int counter = 0;
    int userEntry = 4; // example

    LinkedList[] listsArray = new LinkedList[userEntry];

    while (counter < userEntry){
      listsArray[counter] = new LinkedList<String> ();
      counter++;
    }
  }

Or as you are familiar with LinkedLists, you can create a list of LinkedLists.

public static void main(String[] args) {
    int counter = 0;
    int userEntry = 4; // example

    List<LinkedList<String>> listOfLinkedLists = 
    new LinkedList();

    while (counter < userEntry){
    LinkedList <String> list = new LinkedList<String> ();
      listOfLinkedLists.add(list);
      counter++;
    }
  }

I think what you are stucked at is this.

i'm not sure how to name the lists differently

If you are trying to create variable names at runtime, it will be not an easy task. You can take a look at this SO question too: Assigning variables with dynamic names in Java. But, the better way is to use use an array or a collection like List etc. as I mentioned above.

Tharindu Sathischandra
  • 1,654
  • 1
  • 15
  • 37
0

It seems that based on the comments, you are supposed to do counter++ instead of counter + 1.
counter++ increments counter by one, while counter + 1 only adds 1 to counter and doesn't change the value of counter.

Also, you should store the LinkedLists in an ArrayList where you can get the user input and use a loop to add the number of LinkedLists you want into the ArrayList, then use ArrayList.get(counter) in your loop.

You can also use a for-each loop to loop through the LinkedLists in the ArrayList so you don't have to use a counter. Additionally, you can use a for loop if you need to use the counter in your loop. There are many ways to do this, hope my solution helps you.

Yolomep
  • 173
  • 1
  • 5
  • 16