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.
You may want to use below methods to insert and remove:
e.g.
Mahendrais at index 2(index starts from 0), then to addHarryin front ofMahendra, just do as below:To remove crrent index 4,
To remove previous index 4, which has become index 5 now,