For some reason
query = sc.nextLine();
code returns query""
for the Delete part. So that the second code block does not execute and outputs a wrong list (First index of the list is not removed because of the Delete 0). Any ideas why the second query not get assigned from sc.nextLine()?
public static void main(String[] args) {
final int QUERY_LIMIT = 2;
Scanner sc = new Scanner(System.in);
String query = "";
String insert = "Insert";
String delete = "Delete";
int initial = sc.nextInt();
List<Integer> list = new ArrayList<>();
List <Integer> insertList = new ArrayList<>();
for (int i = 0; i< initial; i++){
list.add(i, sc.nextInt());
}
int numberOfQueries = sc.nextInt();
while (numberOfQueries > 0) {
query = sc.nextLine();
if (insert.equals(query)) {
for (int y = 0; y < QUERY_LIMIT; y++) {
insertList.add(y, sc.nextInt());
}
int insertIndex = insertList.get(0);
int insertValue = insertList.get(1);
list.add(insertIndex,insertValue);
} else if (delete.equals(query)) {
int deleteIndex = sc.nextInt();
list.remove(deleteIndex);
}
numberOfQueries--;
}
sc.close();
list.forEach(a -> System.out.print(a +" "));
}
Sample Input
5
12 0 1 78 12
2
Insert
5 23
Delete
0
Expected Output
0 1 78 12 23
My code output
12 0 1 78 12 23