desislava_topuzakova

07. Simple Text Editor

Jan 12th, 2022
1,251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. package StacksAndQueues_Exercise;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Scanner;
  5.  
  6. public class SimpleTextEditor_07 {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.         int countCommands = Integer.parseInt(scanner.nextLine());
  10.         StringBuilder currentText = new StringBuilder();
  11.  
  12.         ArrayDeque<String> textStack = new ArrayDeque<>();
  13.  
  14.         for (int count = 1; count <= countCommands; count++) {
  15.             String command = scanner.nextLine(); //"{цифра} {параметър}"
  16.             //"1 {string}".split(" ") -> ["1", "{string}"]
  17.             //"2 {count}".split(" ") -> ["2", "{count}"]
  18.             //"3 {index}".split(" ") -> ["3", "{index}"]
  19.             //"4".split(" ") -> ["4"]
  20.             int commandNumber = Integer.parseInt(command.split("\\s+")[0]);// 1, 2, 3, 4
  21.             switch (commandNumber) {
  22.                 case 1:
  23.                     textStack.push(currentText.toString());
  24.                     String stringForAppend = command.split("\\s+")[1];
  25.                     //трябва да добавя stringForAppend към сегашния текст
  26.                     currentText.append(stringForAppend);
  27.                     break;
  28.                 case 2:
  29.                     textStack.push(currentText.toString());
  30.                     int countElementsForDelete = Integer.parseInt(command.split("\\s+")[1]);
  31.                     //изтриваме countElementsForDelete брой елементи
  32.                     //"abcd"
  33.                     int startIndexForDelete = currentText.length() - countElementsForDelete;
  34.                     currentText.delete(startIndexForDelete, currentText.length());
  35.                     break;
  36.                 case 3:
  37.                     int index = Integer.parseInt(command.split("\\s+")[1]);
  38.                     //печатаме елемента на дадения индекс
  39.                     System.out.println(currentText.charAt(index - 1));
  40.                     break;
  41.                 case 4:
  42.                     if (!textStack.isEmpty()) {
  43.                         currentText = new StringBuilder(textStack.pop());
  44.                     }
  45.                     break;
  46.             }
  47.  
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment