Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ArrayList only containing Strings. Print using enhanced for loop [closed]

So here is my program:

Create an ArrayList that will only contain strings Add the following to the list in order

  • Mary
  • John
  • Mahendra
  • Sara
  • Jose
  • Judy

Print the list using the enhanced for loop Insert Harry in front of Mahendra and after John Then Remove position 4 from the list

Here's what I've written:

import java.util.ArrayList;
import java.util.Scanner;

public class Name {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<String>();
        Scanner input = new Scanner(System.in);
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());

        for (String n : names) {
        System.out.println(n);
        }
    }
}

I guess I'm having problems with adding and removing. I believe everything else should be fine though.

like image 613
RazaHuss Avatar asked Nov 04 '22 12:11

RazaHuss


2 Answers

You may want to use below methods to insert and remove:

void    add(int index, E element)
 E      remove(int index)

e.g. Mahendra is at index 2(index starts from 0), then to add Harry in front of Mahendra, just do as below:

  names.add(2, "Harry"); //This will push Mahendra at index 3

To remove crrent index 4,

  names.remove(4);

To remove previous index 4, which has become index 5 now,

  names.remove(5);
like image 173
Yogendra Singh Avatar answered Nov 08 '22 07:11

Yogendra Singh


indexOf() will let you find position of a given entry, add(index, object) will let you insert at an index.

public static void main(String[] args) {
    List<String> names = new ArrayList<String>();

    names.add("Mary");
    names.add("John");
    names.add("Mahendra");
    names.add("Sara");
    names.add("Jose");
    names.add("Judy");

    names.add(names.indexOf("Mahendra"), "Harry");

    for (String name : names) {
        System.out.println(name);
    }
}
like image 40
Adam Avatar answered Nov 08 '22 09:11

Adam