In: Computer Science
Write a Java program that accepts a sequence of commands and print out the number of successful insertions, the number of successful deletions, the number of successful searches (through the “find” command), the number of items remaining in the list after executing all commands and the final contents of the list.
Three commands that will be taken as inputs are “insert”, “delete” and “find”.
Input
Line 1: The number of transactions m on the list, where 1 m 200.
Line 2 to m+1: A string command (“insert”, “delete”, “find”) followed by an integer n (separated by a space).
Output
Line 1: Display 4 integers (each number is separated by a space) which are:
Line 2: The final contents of the list after executing all commands.
Sample Input |
Sample Output |
3 insert 1 delete 5 find 2 |
1 0 0 1 [ 1 ] |
8 find 10 insert 3 insert 2 insert 1 delete 4 delete 3 insert 1 find 2 |
4 1 1 3 [ 1 1 2 ] |
Code
Output
Code to copy
import java.util.*;
class Main{
public static void main(String args[]){
Scanner sc = new
Scanner(System.in);
int m =
sc.nextInt();
sc.nextLine();
ArrayList<Integer>
list = new ArrayList<>();
int insertion = 0,
deletion = 0, search = 0;
while(m > 0){
String input = sc.nextLine();
String[] splited = input.split("\\s+");
if(splited.length < 2){
continue;
}
String command = splited[0];
int n = Integer.parseInt(splited[1]);
if(command.equals("insert")){
insertion++;
list.add(n);
} else if(command.equals("delete")){
int flag = 0;
for(int i = 0; i < list.size(); i++){
if(list.get(i) == n){
flag = 1;
n = i;
}
}
if(flag == 1){
list.remove(n);
deletion++;
}
} else if(command.equals("find")){
int flag = 0;
for(int i = 0; i < list.size(); i++){
if(list.get(i) == n){
flag = 1;
}
}
if(flag == 1){
search++;
}
} else {
System.out.println("Invalid Input");
}
m--;
}
System.out.println(insertion + " " + deletion + " " + search + " "
+ list.size());
System.out.println(list);
}
}
Thank you