Advertisement
Cinder1986

Untitled

Mar 11th, 2022
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.33 KB | None | 0 0
  1. package com.company;
  2. import java.io.*;
  3. import java.util.Set;
  4. import java.util.HashSet;
  5. import java.util.Scanner;
  6. public class Main {
  7. static Scanner scan = new Scanner(System.in);
  8. static byte chooseFileConst = 1;
  9. static byte chooseStartExitConst = 2;
  10. static byte chooseAddConst = 1;
  11. static byte chooseChangeConst = 2;
  12. static byte chooseDeleteConst = 3;
  13. static byte chooseShowConst = 4;
  14. static byte chooseMainExitConst = 5;
  15. static byte maxNumberLength = 3;
  16. static byte maxTownNameLength = 15;
  17. static byte maxTimeLength = 5;
  18. static byte minTimeLength = 4;
  19. static byte maxIntervalTimeLength = 11;
  20. static byte minIntervalTimeLength = 9;
  21. static byte maxHours = 23;
  22. static byte maxMinutes = 59;
  23. static byte maxTicketsLength = 3;
  24. static record trainInfo(String trainNumber, String townName, String time, int ticketsNumber){
  25.  
  26. }
  27. static byte takeStartChoice(){
  28. byte choice = 0;
  29. boolean isCorrect;
  30. do{
  31. isCorrect = true;
  32. try{
  33. choice = Byte.parseByte(scan.nextLine());
  34. }
  35. catch(Exception e){
  36. System.out.print("Произошла ошибка! Введите число ещё раз: ");
  37. isCorrect = false;
  38. }
  39. if (isCorrect && (choice != chooseFileConst && choice != chooseStartExitConst)){
  40. System.out.print("Введено недопустимое значение! Введите число ещё раз: ");
  41. isCorrect = false;
  42. }
  43. }while(!isCorrect);
  44. return choice;
  45. }
  46. static byte takeMainChoice(){
  47. byte choice = 0;
  48. boolean isCorrect;
  49. do{
  50. isCorrect = true;
  51. try{
  52. choice = Byte.parseByte(scan.nextLine());
  53. }
  54. catch(Exception e){
  55. System.out.print("Произошла ошибка! Введите число ещё раз: ");
  56. isCorrect = false;
  57. }
  58. if (isCorrect && (choice != chooseAddConst && choice != chooseChangeConst && choice != chooseDeleteConst && choice != chooseShowConst && choice != chooseMainExitConst)){
  59. System.out.print("Введено недопустимое значение! Введите число ещё раз: ");
  60. isCorrect = false;
  61. }
  62. }while(!isCorrect);
  63. return choice;
  64. }
  65. static boolean checkWriting(String path){
  66. boolean isCorrect = true;
  67. try{
  68. FileWriter writer = new FileWriter(path, true);
  69. writer.append(" ");
  70. }
  71. catch(IOException e){
  72. isCorrect = false;
  73. }
  74. return isCorrect;
  75. }
  76. static String takeFilePath(){
  77. String path;
  78. boolean isCorrect;
  79. do{
  80. isCorrect = true;
  81. path = scan.nextLine();
  82. File file = new File(path);
  83. if(!file.exists() || !checkWriting(path)){
  84. System.out.print("Произошла ошибка! Выберите другой файл или измените настройки данного: ");
  85. isCorrect = false;
  86. }
  87. }while(!isCorrect);
  88. return path;
  89. }
  90. static Set createNameSet(){
  91. Set allowedSymbols = new HashSet();
  92. for(int i = (int)'0';i <= (int)'9';i++){
  93. allowedSymbols.add((char)i);
  94. }
  95. for(int i = (int)'A';i <= (int)'Z';i++){
  96. allowedSymbols.add((char)i);
  97. }
  98. for(int i = (int)'a';i <= (int)'z';i++){
  99. allowedSymbols.add((char)i);
  100. }
  101. for(int i = (int)'А';i <= (int)'Я';i++){
  102. allowedSymbols.add((char)i);
  103. }
  104. for(int i = (int)'а';i <= (int)'я';i++){
  105. allowedSymbols.add((char)i);
  106. }
  107. return allowedSymbols;
  108. }
  109. static boolean checkTrainNumber(String trainNumber){
  110. Set allowedSymbols = createNameSet();
  111. boolean isCorrect;
  112. isCorrect = true;
  113. if(trainNumber.length() > maxNumberLength || trainNumber.length() < 1){
  114. System.out.print("Введен длинный номер! Введите номер ещё раз: ");
  115. isCorrect = false;
  116. }
  117. else{
  118. for(int i = 0;i < trainNumber.length();i++){
  119. if(!allowedSymbols.contains(trainNumber.charAt(i)))
  120. isCorrect = false;
  121. }
  122. if(!isCorrect){
  123. System.out.print("Номер содержит недопустимые символы! Введите номер ещё раз: ");
  124. }
  125. }
  126. return isCorrect;
  127. }
  128. static boolean checkTownName(String townName){
  129. boolean isCorrect;
  130. Set allowedSymbols = createNameSet();
  131. isCorrect = true;
  132. if(townName.length() > maxTownNameLength || townName.length() < 1){
  133. System.out.print("Недопустимая длина названия города! Введите название ещё раз: ");
  134. isCorrect = false;
  135. }
  136. else{
  137. for(int i = 0;i < townName.length();i++){
  138. if(!allowedSymbols.contains(townName.charAt(i)))
  139. isCorrect = false;
  140. }
  141. if(!isCorrect){
  142. System.out.print("Название содержит недопустимые символы! Введите название ещё раз: ");
  143. }
  144. }
  145. return isCorrect;
  146. }
  147. static boolean checkTimeNumber(String number,byte maxValue){
  148. boolean isCorrect = true;
  149. byte temp = 0;
  150. try{
  151. temp = Byte.parseByte(number);
  152. }
  153. catch(Exception e){
  154. isCorrect = false;
  155. }
  156. if(isCorrect && temp > maxValue)
  157. isCorrect = false;
  158. return isCorrect;
  159. }
  160. static boolean checkTimeVal(String time){
  161. boolean isCorrect;
  162. isCorrect = true;
  163. if(time.length() != maxTimeLength && time.length() != minTimeLength){
  164. System.out.print("Произошла ошибка! Введите время ещё раз: ");
  165. isCorrect = false;
  166. }
  167. else if(time.length() == minTimeLength){
  168. if(!(time.charAt(1) == ':' && checkTimeNumber(""+time.charAt(0), maxHours) && checkTimeNumber(""+time.charAt(2)+time.charAt(3),maxMinutes))) {
  169. isCorrect = false;
  170. }
  171. }
  172. else if(time.length() == maxTimeLength) {
  173. if (!(time.charAt(2) == ':' && checkTimeNumber("" + time.charAt(0) + time.charAt(1), maxHours) && checkTimeNumber("" + time.charAt(3) + time.charAt(4), maxMinutes))){
  174. isCorrect = false;
  175. }
  176. }
  177. return isCorrect;
  178. }
  179. static String copy(String line,int index,int count){
  180. String lineCopy = "";
  181. for(int i=index;i<=count+index-1;i++){
  182. lineCopy += line.charAt(i);
  183. }
  184. return lineCopy;
  185. }
  186. static boolean checkTime(String time){
  187. boolean isCorrect;
  188. byte separator, i;
  189. separator = 1;
  190. if(time.length() > maxIntervalTimeLength || time.length() < maxIntervalTimeLength)
  191. return false;
  192. else
  193. isCorrect = false;
  194. i = 4;
  195. while(!isCorrect && i < 6){
  196. if(time.charAt(i)=='-'){
  197. separator = i;
  198. isCorrect = true;
  199. }
  200. i++;
  201. }
  202. if (isCorrect && !(checkTimeVal(copy(time,0,separator)) && checkTimeVal(copy(time,separator+1,time.length()-separator-1))))
  203. isCorrect = false;
  204. return isCorrect;
  205. }
  206. static boolean checkTickets(String tickets){
  207. byte temp = 0;
  208. boolean isCorrect;
  209. isCorrect = true;
  210. if(tickets.length() > maxTicketsLength || tickets.length() < 1) {
  211. System.out.print("Слишком большое количество билетов! Введите количество ещё раз: ");
  212. isCorrect = false;
  213. }
  214. else{
  215. try {
  216. temp = Byte.parseByte(tickets);
  217. }
  218. catch (Exception e){
  219. System.out.print("Произошла ошибка! Введите число ещё раз: ");
  220. isCorrect = false;
  221. }
  222. if(isCorrect && temp < 0){
  223. System.out.print("Недопустимое значение! Введите число ещё раз: ");
  224. isCorrect = false;
  225. }
  226. }
  227. return isCorrect;
  228. }
  229. static int countWords(String line){
  230. int counter = 0;
  231. for(int i=0;i<line.length();i++){
  232. if(line.charAt(i)==' ')
  233. counter++;
  234. else if(i == line.length() - 1)
  235. counter++;
  236. }
  237. return counter;
  238. }
  239. static String[] takeWords(String line){
  240. String[] words = new String[countWords(line)];
  241. byte element = 0;
  242. String word = "";
  243. for(int i=0;i<line.length();i++){
  244. if(line.charAt(i)==' '){
  245. words[element] = word;
  246. element++;
  247. word = "";
  248. }
  249. else if(i == line.length() - 1){
  250. word += line.charAt(i);
  251. words[element] = word;
  252. }
  253. else
  254. word += line.charAt(i);
  255. }
  256. return words;
  257. }
  258. static String takeDataFile() throws FileNotFoundException{
  259. String path;
  260. boolean isCorrect;
  261. String[] words;
  262. String line;
  263. do {
  264. isCorrect = true;
  265. path = takeFilePath();
  266. Scanner scanFile = new Scanner(new File(path));
  267. while(isCorrect && scanFile.hasNext()){
  268. line = scanFile.nextLine();
  269. words = takeWords(line);
  270. if(!(checkTrainNumber(words[0]) && checkTownName(words[1]) && checkTime(words[2]) && checkTickets(words[3]))) {
  271. System.out.print("Произошла ошибка при попытке прочитать данные из файла! Выберите другой файл или проверьте верность данного: ");
  272. isCorrect = false;
  273. }
  274. }
  275. scanFile.close();
  276. }while (!isCorrect);
  277. return path;
  278. }
  279. static String takeTrainNumber(){
  280. String trainNumber;
  281. boolean isCorrect;
  282. do{
  283. isCorrect = true;
  284. trainNumber = scan.nextLine();
  285. if(!checkTrainNumber(trainNumber))
  286. isCorrect = false;
  287. }while(!isCorrect);
  288. return trainNumber;
  289. }
  290. static String takeTownName(){
  291. String townName;
  292. boolean isCorrect;
  293. do{
  294. isCorrect = true;
  295. townName = scan.nextLine();
  296. if(!checkTownName(townName))
  297. isCorrect = false;
  298. }while (!isCorrect);
  299. return townName;
  300. }
  301. static String takeTime(){
  302. String time;
  303. boolean isCorrect;
  304. do {
  305. isCorrect = true;
  306. time = scan.nextLine();
  307. if(!checkTime(time)) {
  308. System.out.print("Произошла ошибка! Введите время ещё раз: ");
  309. isCorrect = false;
  310. }
  311. }while(!isCorrect);
  312. return time;
  313. }
  314. static String takeTickets(){
  315. String tickets;
  316. boolean isCorrect;
  317. do {
  318. isCorrect = true;
  319. tickets = scan.nextLine();
  320. if(!checkTickets(tickets))
  321. isCorrect = false;
  322. }while(!isCorrect);
  323. return tickets;
  324. }
  325. static void writeToFile(String path, String trainNumber, String townName, String leaveTime, String ticketsNumber){
  326. try{
  327. FileWriter writer = new FileWriter(path, true);
  328. writer.append('\n' + trainNumber + ' ' + townName + ' ' + leaveTime + ' ' + ticketsNumber);
  329. writer.close();
  330. }
  331. catch (IOException e){
  332. System.out.println("Произошла ошибка при попытке записать данные в файл!");
  333. }
  334. }
  335. static boolean checkIfExists(String number, String path) throws FileNotFoundException{
  336. boolean isFound = false;
  337. String[] words;
  338. Scanner scanFile = new Scanner(new File(path));
  339. while(!isFound && scanFile.hasNext()){
  340. words = takeWords(scanFile.nextLine());
  341. if(number.equals(words[0]))
  342. isFound = true;
  343. }
  344. scanFile.close();
  345. return isFound;
  346. }
  347. static String takeOldNumber(String path) throws FileNotFoundException{
  348. String number;
  349. boolean isCorrect;
  350. do{
  351. isCorrect = true;
  352. number = takeTrainNumber();
  353. if(!checkIfExists(number, path)){
  354. System.out.print("Данный состав не найден! Введите номер существующего состава: ");
  355. isCorrect = false;
  356. }
  357. }while(!isCorrect);
  358. return number;
  359. }
  360. static String takeChangeLine(String number, String path) throws FileNotFoundException{
  361. Scanner scanFile = new Scanner(new File(path));
  362. String[] words;
  363. String line = "";
  364. while(scanFile.hasNext()){
  365. words = takeWords(scanFile.nextLine());
  366. if(number.equals(words[0])){
  367. line = words[0] +' '+ words[1] +' '+ words[2] +' '+ words[3];
  368. }
  369. }
  370. return line;
  371. }
  372. static void changeRecord(trainInfo newTrain,String oldNumber, String path, String correctionPath) throws IOException{
  373. Scanner scanFile = new Scanner(new File(path));
  374. FileWriter writer = new FileWriter(correctionPath);
  375. String[] words;
  376. while(scanFile.hasNext()){
  377. words = takeWords(scanFile.nextLine());
  378. if(words[0].equals(oldNumber)){
  379. writer.write(newTrain.ticketsNumber + " " + newTrain.townName + ' ' + newTrain.time + ' ' + newTrain.ticketsNumber +'\n');
  380. }
  381. else{
  382. writer.write(words[0] +' '+ words[1] +' '+ words[2] +' '+ words[3] +'\n');
  383. }
  384. }
  385. scanFile.close();
  386. writer.close();
  387. }
  388. static void deleteLine(String number, String dataPath, String correctionPath) throws IOException{
  389. Scanner scanFile = new Scanner(new File(dataPath));
  390. BufferedWriter writer = new BufferedWriter(new FileWriter(correctionPath));
  391. String[] words;
  392. while(scanFile.hasNext()){
  393. words = takeWords(scanFile.nextLine());
  394. if(!number.equals(words[0])){
  395. writer.write(words[0]+' '+words[1]+' '+words[2]+' '+words[3]+'\n');
  396. }
  397. }
  398. writer.close();
  399. scanFile.close();
  400. }
  401. static void addRecordToFile(String path){
  402. String trainNumber, townName, leaveTime, ticketsNumber;
  403. System.out.print("Введите номер состава: ");
  404. trainNumber = takeTrainNumber();
  405. System.out.print("Введите название города прибытия: ");
  406. townName = takeTownName();
  407. System.out.print("Введите время отъезда/прибытия: ");
  408. leaveTime = takeTime();
  409. System.out.print("Введите количество билетов на поезд: ");
  410. ticketsNumber = takeTickets();
  411. writeToFile(path, trainNumber,townName,leaveTime,ticketsNumber);
  412. System.out.println("Изменения успешно внесены!");
  413. }
  414. static void changeRecordInFile(String path, String correctionPath) throws IOException{
  415. String oldNumber, line;
  416. byte choice;
  417. System.out.print("Введите номер состава, информацию о котором хотите изменить: ");
  418. oldNumber = takeOldNumber(path);
  419. line = takeChangeLine(oldNumber, path);
  420. String[] words = takeWords(line);
  421. System.out.println("1.Изменить номер состава\n2.Оставить");
  422. choice = takeStartChoice();
  423. if(choice == chooseFileConst){
  424. System.out.println("Введите номер нового состава:");
  425. String trainNumber = takeTrainNumber();
  426. words[0] = trainNumber;
  427. }
  428. System.out.println("1.Изменить город назначения\n2.Оставить");
  429. choice = takeStartChoice();
  430. if(choice == chooseFileConst){
  431. System.out.println("Введите новый город назначения:");
  432. String townName = takeTownName();
  433. words[1] = townName;
  434. }
  435. System.out.println("1.Изменить время отъезда/прибытия\n2.Оставить");
  436. choice = takeStartChoice();
  437. if(choice == chooseFileConst){
  438. System.out.println("Введите новое время отъезда/прибытия:");
  439. String leaveTime = takeTime();
  440. words[2] = leaveTime;
  441. }
  442. System.out.println("1.Изменить количество билетов\n2.Оставить");
  443. choice = takeStartChoice();
  444. if(choice == chooseFileConst){
  445. System.out.println("Введите новое количество билетов:");
  446. String tickets = takeTickets();
  447. words[3] = tickets;
  448. }
  449. trainInfo newTrain = new trainInfo(words[0], words[1], words[2], Integer.parseInt(words[3]));
  450. changeRecord(newTrain, oldNumber, path, correctionPath);
  451. System.out.println("Изменения успешно внесены!");
  452. }
  453. static void deleteRecordInFile(String dataPath, String correctionPath) throws IOException{
  454. System.out.print("Введите номер состава, информацию о котором хотите удалить: ");
  455. String trainNumber = takeOldNumber(dataPath);
  456. deleteLine(trainNumber, dataPath, correctionPath);
  457. System.out.print("Изменения успешно сохранены!");
  458. }
  459. static void showRecordsFromFile(String path) throws FileNotFoundException{
  460. System.out.println("Расписание поездов:");
  461. Scanner scanFile = new Scanner(new File(path));
  462. while(scanFile.hasNext())
  463. System.out.println(scanFile.nextLine());
  464. scanFile.close();
  465. }
  466. public static void main(String[] args) throws IOException{
  467. System.out.println("Данная программа позволяет взаимодействовать с расписанием поездов\n1.Выбрать файл\n2.Выйти");
  468. byte choiceVar = takeStartChoice();
  469. String dataFilePath, correctionFilePath;
  470. if (choiceVar == chooseFileConst){
  471. System.out.println("Введите путь к файлу с данными:");
  472. dataFilePath = takeDataFile();
  473. System.out.println("Выберите одну из опций.\n1.Добавить сведения\n2.Изменить сведения\n3.Удалить сведения\n4.Показать сведения");
  474. choiceVar = takeMainChoice();
  475. if(choiceVar == chooseAddConst){
  476. addRecordToFile(dataFilePath);
  477. }
  478. else if(choiceVar == chooseChangeConst){
  479. System.out.println("Введите путь к файлу корректюр:");
  480. correctionFilePath = takeFilePath();
  481. changeRecordInFile(dataFilePath, correctionFilePath);
  482. }
  483. else if(choiceVar == chooseDeleteConst){
  484. System.out.println("Введите путь к файлу корректюр:");
  485. correctionFilePath = takeFilePath();
  486. deleteRecordInFile(dataFilePath,correctionFilePath);
  487. }
  488. else if(choiceVar == chooseShowConst){
  489. showRecordsFromFile(dataFilePath);
  490. }
  491. }
  492. scan.close();
  493. }
  494. }
  495.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement