-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextEditor.java
More file actions
70 lines (63 loc) · 3.09 KB
/
TextEditor.java
File metadata and controls
70 lines (63 loc) · 3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class TextEditor {
public String swapTwoRows(int firstRow, int secondRow, Reader input) throws IOException {
if (firstRow < 0 || secondRow < 0 || input == null) {
throw new IllegalArgumentException("Arguments must be positive");
}
ArrayList<String> listOfRows = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(input);
listOfRows = (ArrayList<String>) reader.lines().collect(Collectors.toList());
Collections.swap(listOfRows, firstRow, secondRow);
reader.close();
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Rows out of bounds");
}
String updatedDate = String.join("\n", listOfRows);
writeToFile(updatedDate);
return updatedDate;
}
public String swapTwoWords(int firstRow, int indexOfFirstWord, int secondRow, int indexOfSecondWord, Reader input) throws IOException {
if (firstRow < 0 || secondRow < 0 || indexOfFirstWord < 0 || indexOfSecondWord < 0 || input == null) {
throw new IllegalArgumentException("Arguments must be positive");
}
ArrayList<String> listOfRows = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(input);
listOfRows = (ArrayList<String>) reader.lines().collect(Collectors.toList());
reader.close();
if (firstRow != secondRow) {
String first = listOfRows.get(firstRow);
String[] wordsFirst = first.split("\\s+");
String second = listOfRows.get(secondRow);
String[] wordsSecond = second.split("\\s+");
first = first.replaceAll(wordsFirst[indexOfFirstWord], wordsSecond[indexOfSecondWord]);
second = second.replaceAll(wordsSecond[indexOfSecondWord], wordsFirst[indexOfFirstWord]);
listOfRows.set(firstRow, first);
listOfRows.set(secondRow, second);
} else {
String first = listOfRows.get(firstRow);
String[] wordsFirst = first.split("\\s+");
Collections.swap(Arrays.asList(wordsFirst), indexOfFirstWord, indexOfSecondWord);
first = String.join(" ", wordsFirst);
listOfRows.set(firstRow, first);
}
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Out of bounds arguments");
}
String updatedDate = String.join("\n", listOfRows);
writeToFile(updatedDate);
return updatedDate;
}
public static void writeToFile(String data) throws IOException {
if (data == null) {
throw new IllegalArgumentException("Data is null");
}
FileWriter writeToFile = new FileWriter(("filename.txt"), false);
writeToFile.write(data);
writeToFile.flush();
writeToFile.close();
}
}