Advertisement
desislava_topuzakova

02. Change List

Oct 14th, 2022
446
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. package lists;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.stream.Collectors;
  7.  
  8. public class ChangeList_02 {
  9. public static void main(String[] args) {
  10. Scanner scanner = new Scanner(System.in);
  11. //1. списък с числа -> входни данни
  12. //2. получаваме команди -> "end"
  13. //"Delete {element}" -> "Delete 3"
  14. //"Insert {element} {position}" -> "Insert 3 1"
  15.  
  16. List<Integer> numbers = Arrays.stream(scanner.nextLine() //"1 2 3 4 5 5 5 6"
  17. .split(" ")) //["1", "2", "3", "4", "5", "5", "5", "6"] -> масив от текстове
  18. .map(Integer::parseInt) //[1, 2, 3, 4, 5, 5, 5, 6] -> масив от цели числа
  19. .collect(Collectors.toList()); //{1, 2, 3, 4, 5, 5, 5, 6} -> списък от цели числа
  20.  
  21. String command = scanner.nextLine(); //команди
  22. //stop: command == "end"
  23. //continue: command != "end"
  24. while (!command.equals("end")) {
  25. //команда
  26. //1. command = "Delete 3"
  27. if (command.contains("Delete")) {
  28. //"Delete 3".split(" ") -> ["Delete", "3"]
  29. int numberForRemove = Integer.parseInt(command.split(" ")[1]);
  30. //премахваме всички стойности от списъка равни на numberForRemove
  31. numbers.removeAll(Arrays.asList(numberForRemove));
  32. }
  33. //2. command = "Insert 3 1"
  34. else if (command.contains("Insert")) {
  35. //"Insert 3 1".split(" ") -> ["Insert", "3", "1"]
  36. //вмъкна element на index
  37. int element = Integer.parseInt(command.split(" ")[1]);
  38. int index = Integer.parseInt(command.split(" ")[2]);
  39. numbers.add(index, element);
  40. }
  41. command = scanner.nextLine();
  42. }
  43.  
  44. //списък с числа -> {3, 4, 5, 6}
  45. for (int number : numbers) {
  46. System.out.print(number + " ");
  47. }
  48.  
  49. }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement