Problem statement
Program to insert, remove elements from array according to instruction
In this java program, we are taking 3 types of input from user like “insert” or “remove” or “exit”.
- If user entered “insert”, take again input as element of array from user.
- If user entered “remove”, take input as index of array from user.
- If user entered “exit”, print output and exit from program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util. * ; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System. in ); boolean flag = true; ArrayList arr = new ArrayList(); while (flag) { //Take input "insert/remove/exit" from user String command = sc.next(); //Take input element int ele = sc.nextInt(); if (command.equals("exit")) { flag = false; } else if (command.equals("insert")) { arr.add(ele); } else if (command.equals("remove")) { arr.remove(ele); } System.out.println(arr); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Enter a input instruction insert Enter array element 10 [10] Enter a input instruction insert Enter array element 20 [10, 20] Enter a input instruction insert Enter array element 30 [10, 20, 30] Enter a input instruction remove Enter array element 1 [10, 30] Enter a input instruction exit [10, 30] |
In above program, we took 3 types of input from user. If the input is “insert” then we added element into array. If the user entered “remove” then element at index should be removed from array. If input is “exit” exit from console and print final array.