Задача 2. Change List дава Runtime error на единия от тестовете
Здравейте,
Не можах да открия къде се дъни.
Моля помогнете да намеря грешката.
Приятен ден!
Задачата е :
Write a program, which reads a list of integers from the console and receives commands, which manipulate the list. Your program may receive the following commands:
- Delete {element} – delete all elements in the array, which are equal to the given element
- Insert {element} {position} – insert element and the given position
You should stop the program when you receive the command "end". Print all numbers in the array separated with single whitespace.
Examples
|
Input |
Output |
|
1 2 3 4 5 5 5 6 Delete 5 Insert 10 1 Delete 5 end |
1 10 2 3 4 6 |
|
20 12 4 319 21 31234 2 41 23 4 Insert 50 2 Insert 50 5 Delete 4 end |
20 12 50 319 50 21 31234 2 41 23
|
Решението ми е:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
List<Integer> intList = new ArrayList<Integer>();
int[] intArr=Arrays.stream(sc.nextLine().split(" ")).mapToInt(e->Integer.parseInt(e)).toArray();
for (int i:intArr){
intList.add(i);
}
String strInput="";
while(!(strInput=sc.nextLine().toLowerCase()).equals("end")){
String[] inputArr=strInput.split(" ");
switch (inputArr[0]){
case "insert":
int element=Integer.parseInt(inputArr[1]);
int index=Integer.parseInt(inputArr[2]);
if (index >= 0 && index < intList.size()){
intList.add(index,element);
}
break;
case "delete":{
int searchVal=Integer.parseInt(inputArr[1]);
intList.removeAll(Collections.singleton(searchVal));
break;
}
}
}
for (int i=0;i<intList.size();i++){
System.out.printf("%d ",intList.get(i));
}
}
}
Благодаря, явно е време да науча regex .
Некоректно е ,че никъде в условието не беше казано,че може да има повече от един интервал във входните данни.
Успех!