Write a java program to remove nth numbers element from ArrayList

Write a program that accepts an ArrayList of integers as input and removes every 3rd element and prints the final ArrayList.

Suppose the given arrayList contains 10 elements remove the 3rd, 6th and 9th elements.

Input and Output Format:

The first line of the input consists of an integer n, that corresponds to the number of elements to be added in the ArrayList.

The next n lines consist of integers that correspond to the elements in the ArrayList.

Output consists of an ArrayList of integers.

Sample Input:

6

3

1

11

19

17

19

Sample Output

3

1

19

17

java program to remove nth numbers element from ArrayList

package com.demo;
 
import java.util.*;
 
public class Main {
 
private static Scanner sc;
 
public static void main(String[] args) {
sc = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList<Integer>();
ArrayList<Integer> al1 = new ArrayList<Integer>();
int n = Integer.parseInt(sc.nextLine());
for (int i = 0; i < n; i++) {
al.add(sc.nextInt());
}
al1 = findFruitName(al);
Iterator it = al1.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
 
public static ArrayList<Integer> findFruitName(ArrayList<Integer> al) {
ArrayList<Integer> al2 = new ArrayList<Integer>();
 
for (int i = 0; i < al.size(); i++) {
if ((i + 1) % 3 != 0)
al2.add(al.get(i));
}
 
return al2;
}
}

Add a Comment

Your email address will not be published. Required fields are marked *

seventeen − 6 =