Advertisement
desislava_topuzakova

Untitled

Mar 24th, 2023
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. package ExamPreparation2;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class WorldTour_01 {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8.  
  9. String allStops = scanner.nextLine(); //всички спирки: "Hawai::Cyprys-Greece"
  10. StringBuilder stopsBuilder = new StringBuilder(allStops);
  11.  
  12. String command = scanner.nextLine();
  13. while(!command.equals("Travel")) {
  14. //команда
  15. if (command.contains("Add Stop")) {
  16. //command = "Add Stop:2:Italy".split(":") -> ["Add Stop", "2", "Italy"]
  17. int index = Integer.parseInt(command.split(":")[1]); //индекс, на който трябва да вмъкнем спирка
  18. String stopName = command.split(":")[2]; //спирка, която трябва да вмъкнем
  19.  
  20. //валидирам индекса
  21. //първия (0) до последния индекс (дължина - 1)
  22. if (isValidIndex(index, stopsBuilder)) {
  23. stopsBuilder.insert(index, stopName);
  24. }
  25.  
  26. } else if (command.contains("Remove Stop")) {
  27. //command = "Remove Stop:2:9".split(":") -> ["Remove Stop", "2", "9"]
  28. int startIndex = Integer.parseInt(command.split(":")[1]);
  29. int endIndex = Integer.parseInt(command.split(":")[2]);
  30.  
  31. //валидираме индексите
  32. if (isValidIndex(startIndex, stopsBuilder) && isValidIndex(endIndex, stopsBuilder)) {
  33. stopsBuilder.delete(startIndex, endIndex + 1);
  34. }
  35.  
  36. } else if (command.contains("Switch")) {
  37. //command = "Switch:Italy:Spain".split(":") -> ["Switch", "Italy", "Spain"]
  38. String oldText = command.split(":")[1];
  39. String newText = command.split(":")[2];
  40.  
  41. //!!! правим замяната на стария с новия, само ако стария съществува
  42. if (stopsBuilder.toString().contains(oldText)) {
  43. String updatedText = stopsBuilder.toString().replace(oldText, newText); //текст след заместването
  44. stopsBuilder = new StringBuilder(updatedText);
  45. }
  46. }
  47.  
  48. System.out.println(stopsBuilder);
  49. command = scanner.nextLine();
  50. }
  51.  
  52. System.out.println("Ready for world tour! Planned stops: " + stopsBuilder);
  53.  
  54.  
  55. }
  56.  
  57. //метод, който валидира индекс в текст stopsBuilder
  58. //true -> ако индексът е валиден
  59. //false -> ако индексът не е валиден
  60. public static boolean isValidIndex (int index, StringBuilder builder) {
  61. //първия (0) до последния индекс (дължина - 1)
  62. return index >= 0 && index <= builder.length() - 1;
  63. //return index >= 0 && index < builder.length();
  64. }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement