Advertisement
desislava_topuzakova

01. World Tour

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