2

I have written this:

public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<>();//declare your list
    Scanner input = new Scanner(System.in);//create a scanner
    System.out.println("How many participants? ");
    int nbr = input.nextInt();//read the number of element
    input.nextLine();
    do {
        System.out.println("What is the name of the people?");
        list.add(input.nextLine());//read and insert into your list in one shot
        nbr--;//decrement the index
    } while (nbr > 0);//repeat until the index will be 0

    System.out.println(list);//print your list

The output is:

Jack, Frank

What I want to do is changing the content of the linked list. For example I wrote 2 names Jack and Frank. Then I want to add Jack's surname so that linked list will be:

Jack Adam, Frank

What should I do?

equasezy
  • 45
  • 1
  • 7
  • 1
    Possible duplicate of [How do I update the element at a certain position in an ArrayList?](https://stackoverflow.com/questions/4352885/how-do-i-update-the-element-at-a-certain-position-in-an-arraylist) – Ivar Apr 26 '18 at 21:00
  • It just changes the index of the list. For example I wrote list.set(0, Adam); it just crates a new node with Adam. Doesn't change the content. – equasezy Apr 26 '18 at 21:04
  • No, it changes the value **at** the index in the list. `list.set(0, "Jack Adam")` will do what you ask. – Ivar Apr 26 '18 at 21:05
  • I don't want to write "Jack" again that's the problem. I want to just write Adam and it will add the "Adam" to the Jack. – equasezy Apr 26 '18 at 21:07
  • 1
    Well, then you need to get and set the same index, as shown in Glim's answer. – Ivar Apr 26 '18 at 21:08

1 Answers1

1

What you need to do is use the set method updating the specific position that you want to update. In this case will be something like this:

list.set(0, list.get(0) + " Adam");

Notice that we are getting the content of the position 0 of the list and concatenating with the surname.

Glim
  • 361
  • 1
  • 10
  • Thank you this is what I was looking for I will mark this as a answer after "You can accept this after x min" thing! – equasezy Apr 26 '18 at 21:09