Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.*;
- import java.util.Set;
- import java.util.HashSet;
- import java.util.Scanner;
- public class Main {
- static Scanner scan = new Scanner(System.in);
- static byte chooseFileConst = 1;
- static byte chooseStartExitConst = 2;
- static byte chooseAddConst = 1;
- static byte chooseChangeConst = 2;
- static byte chooseDeleteConst = 3;
- static byte chooseShowConst = 4;
- static byte chooseMainExitConst = 5;
- static byte maxNumberLength = 3;
- static byte maxTownNameLength = 15;
- static byte maxTimeLength = 5;
- static byte minTimeLength = 4;
- static byte maxIntervalTimeLength = 11;
- static byte minIntervalTimeLength = 9;
- static byte maxHours = 23;
- static byte maxMinutes = 59;
- static byte maxTicketsLength = 3;
- static record trainInfo(String trainNumber, String townName, String time, int ticketsNumber){
- }
- static byte takeStartChoice(){
- byte choice = 0;
- boolean isCorrect;
- do{
- isCorrect = true;
- try{
- choice = Byte.parseByte(scan.nextLine());
- }
- catch(Exception e){
- System.out.print("Произошла ошибка! Введите число ещё раз: ");
- isCorrect = false;
- }
- if (isCorrect && (choice != chooseFileConst && choice != chooseStartExitConst)){
- System.out.print("Введено недопустимое значение! Введите число ещё раз: ");
- isCorrect = false;
- }
- }while(!isCorrect);
- return choice;
- }
- static byte takeMainChoice(){
- byte choice = 0;
- boolean isCorrect;
- do{
- isCorrect = true;
- try{
- choice = Byte.parseByte(scan.nextLine());
- }
- catch(Exception e){
- System.out.print("Произошла ошибка! Введите число ещё раз: ");
- isCorrect = false;
- }
- if (isCorrect && (choice != chooseAddConst && choice != chooseChangeConst && choice != chooseDeleteConst && choice != chooseShowConst && choice != chooseMainExitConst)){
- System.out.print("Введено недопустимое значение! Введите число ещё раз: ");
- isCorrect = false;
- }
- }while(!isCorrect);
- return choice;
- }
- static boolean checkWriting(String path){
- boolean isCorrect = true;
- try{
- FileWriter writer = new FileWriter(path, true);
- writer.append(" ");
- }
- catch(IOException e){
- isCorrect = false;
- }
- return isCorrect;
- }
- static String takeFilePath(){
- String path;
- boolean isCorrect;
- do{
- isCorrect = true;
- path = scan.nextLine();
- File file = new File(path);
- if(!file.exists() || !checkWriting(path)){
- System.out.print("Произошла ошибка! Выберите другой файл или измените настройки данного: ");
- isCorrect = false;
- }
- }while(!isCorrect);
- return path;
- }
- static Set createNameSet(){
- Set allowedSymbols = new HashSet();
- for(int i = (int)'0';i <= (int)'9';i++){
- allowedSymbols.add((char)i);
- }
- for(int i = (int)'A';i <= (int)'Z';i++){
- allowedSymbols.add((char)i);
- }
- for(int i = (int)'a';i <= (int)'z';i++){
- allowedSymbols.add((char)i);
- }
- for(int i = (int)'А';i <= (int)'Я';i++){
- allowedSymbols.add((char)i);
- }
- for(int i = (int)'а';i <= (int)'я';i++){
- allowedSymbols.add((char)i);
- }
- return allowedSymbols;
- }
- static boolean checkTrainNumber(String trainNumber){
- Set allowedSymbols = createNameSet();
- boolean isCorrect;
- isCorrect = true;
- if(trainNumber.length() > maxNumberLength || trainNumber.length() < 1){
- System.out.print("Введен длинный номер! Введите номер ещё раз: ");
- isCorrect = false;
- }
- else{
- for(int i = 0;i < trainNumber.length();i++){
- if(!allowedSymbols.contains(trainNumber.charAt(i)))
- isCorrect = false;
- }
- if(!isCorrect){
- System.out.print("Номер содержит недопустимые символы! Введите номер ещё раз: ");
- }
- }
- return isCorrect;
- }
- static boolean checkTownName(String townName){
- boolean isCorrect;
- Set allowedSymbols = createNameSet();
- isCorrect = true;
- if(townName.length() > maxTownNameLength || townName.length() < 1){
- System.out.print("Недопустимая длина названия города! Введите название ещё раз: ");
- isCorrect = false;
- }
- else{
- for(int i = 0;i < townName.length();i++){
- if(!allowedSymbols.contains(townName.charAt(i)))
- isCorrect = false;
- }
- if(!isCorrect){
- System.out.print("Название содержит недопустимые символы! Введите название ещё раз: ");
- }
- }
- return isCorrect;
- }
- static boolean checkTimeNumber(String number,byte maxValue){
- boolean isCorrect = true;
- byte temp = 0;
- try{
- temp = Byte.parseByte(number);
- }
- catch(Exception e){
- isCorrect = false;
- }
- if(isCorrect && temp > maxValue)
- isCorrect = false;
- return isCorrect;
- }
- static boolean checkTimeVal(String time){
- boolean isCorrect;
- isCorrect = true;
- if(time.length() != maxTimeLength && time.length() != minTimeLength){
- System.out.print("Произошла ошибка! Введите время ещё раз: ");
- isCorrect = false;
- }
- else if(time.length() == minTimeLength){
- if(!(time.charAt(1) == ':' && checkTimeNumber(""+time.charAt(0), maxHours) && checkTimeNumber(""+time.charAt(2)+time.charAt(3),maxMinutes))) {
- isCorrect = false;
- }
- }
- else if(time.length() == maxTimeLength) {
- if (!(time.charAt(2) == ':' && checkTimeNumber("" + time.charAt(0) + time.charAt(1), maxHours) && checkTimeNumber("" + time.charAt(3) + time.charAt(4), maxMinutes))){
- isCorrect = false;
- }
- }
- return isCorrect;
- }
- static String copy(String line,int index,int count){
- String lineCopy = "";
- for(int i=index;i<=count+index-1;i++){
- lineCopy += line.charAt(i);
- }
- return lineCopy;
- }
- static boolean checkTime(String time){
- boolean isCorrect;
- byte separator, i;
- separator = 1;
- if(time.length() > maxIntervalTimeLength || time.length() < maxIntervalTimeLength)
- return false;
- else
- isCorrect = false;
- i = 4;
- while(!isCorrect && i < 6){
- if(time.charAt(i)=='-'){
- separator = i;
- isCorrect = true;
- }
- i++;
- }
- if (isCorrect && !(checkTimeVal(copy(time,0,separator)) && checkTimeVal(copy(time,separator+1,time.length()-separator-1))))
- isCorrect = false;
- return isCorrect;
- }
- static boolean checkTickets(String tickets){
- byte temp = 0;
- boolean isCorrect;
- isCorrect = true;
- if(tickets.length() > maxTicketsLength || tickets.length() < 1) {
- System.out.print("Слишком большое количество билетов! Введите количество ещё раз: ");
- isCorrect = false;
- }
- else{
- try {
- temp = Byte.parseByte(tickets);
- }
- catch (Exception e){
- System.out.print("Произошла ошибка! Введите число ещё раз: ");
- isCorrect = false;
- }
- if(isCorrect && temp < 0){
- System.out.print("Недопустимое значение! Введите число ещё раз: ");
- isCorrect = false;
- }
- }
- return isCorrect;
- }
- static int countWords(String line){
- int counter = 0;
- for(int i=0;i<line.length();i++){
- if(line.charAt(i)==' ')
- counter++;
- else if(i == line.length() - 1)
- counter++;
- }
- return counter;
- }
- static String[] takeWords(String line){
- String[] words = new String[countWords(line)];
- byte element = 0;
- String word = "";
- for(int i=0;i<line.length();i++){
- if(line.charAt(i)==' '){
- words[element] = word;
- element++;
- word = "";
- }
- else if(i == line.length() - 1){
- word += line.charAt(i);
- words[element] = word;
- }
- else
- word += line.charAt(i);
- }
- return words;
- }
- static String takeDataFile() throws FileNotFoundException{
- String path;
- boolean isCorrect;
- String[] words;
- String line;
- do {
- isCorrect = true;
- path = takeFilePath();
- Scanner scanFile = new Scanner(new File(path));
- while(isCorrect && scanFile.hasNext()){
- line = scanFile.nextLine();
- words = takeWords(line);
- if(!(checkTrainNumber(words[0]) && checkTownName(words[1]) && checkTime(words[2]) && checkTickets(words[3]))) {
- System.out.print("Произошла ошибка при попытке прочитать данные из файла! Выберите другой файл или проверьте верность данного: ");
- isCorrect = false;
- }
- }
- scanFile.close();
- }while (!isCorrect);
- return path;
- }
- static String takeTrainNumber(){
- String trainNumber;
- boolean isCorrect;
- do{
- isCorrect = true;
- trainNumber = scan.nextLine();
- if(!checkTrainNumber(trainNumber))
- isCorrect = false;
- }while(!isCorrect);
- return trainNumber;
- }
- static String takeTownName(){
- String townName;
- boolean isCorrect;
- do{
- isCorrect = true;
- townName = scan.nextLine();
- if(!checkTownName(townName))
- isCorrect = false;
- }while (!isCorrect);
- return townName;
- }
- static String takeTime(){
- String time;
- boolean isCorrect;
- do {
- isCorrect = true;
- time = scan.nextLine();
- if(!checkTime(time)) {
- System.out.print("Произошла ошибка! Введите время ещё раз: ");
- isCorrect = false;
- }
- }while(!isCorrect);
- return time;
- }
- static String takeTickets(){
- String tickets;
- boolean isCorrect;
- do {
- isCorrect = true;
- tickets = scan.nextLine();
- if(!checkTickets(tickets))
- isCorrect = false;
- }while(!isCorrect);
- return tickets;
- }
- static void writeToFile(String path, String trainNumber, String townName, String leaveTime, String ticketsNumber){
- try{
- FileWriter writer = new FileWriter(path, true);
- writer.append('\n' + trainNumber + ' ' + townName + ' ' + leaveTime + ' ' + ticketsNumber);
- writer.close();
- }
- catch (IOException e){
- System.out.println("Произошла ошибка при попытке записать данные в файл!");
- }
- }
- static boolean checkIfExists(String number, String path) throws FileNotFoundException{
- boolean isFound = false;
- String[] words;
- Scanner scanFile = new Scanner(new File(path));
- while(!isFound && scanFile.hasNext()){
- words = takeWords(scanFile.nextLine());
- if(number.equals(words[0]))
- isFound = true;
- }
- scanFile.close();
- return isFound;
- }
- static String takeOldNumber(String path) throws FileNotFoundException{
- String number;
- boolean isCorrect;
- do{
- isCorrect = true;
- number = takeTrainNumber();
- if(!checkIfExists(number, path)){
- System.out.print("Данный состав не найден! Введите номер существующего состава: ");
- isCorrect = false;
- }
- }while(!isCorrect);
- return number;
- }
- static String takeChangeLine(String number, String path) throws FileNotFoundException{
- Scanner scanFile = new Scanner(new File(path));
- String[] words;
- String line = "";
- while(scanFile.hasNext()){
- words = takeWords(scanFile.nextLine());
- if(number.equals(words[0])){
- line = words[0] +' '+ words[1] +' '+ words[2] +' '+ words[3];
- }
- }
- return line;
- }
- static void changeRecord(trainInfo newTrain,String oldNumber, String path, String correctionPath) throws IOException{
- Scanner scanFile = new Scanner(new File(path));
- FileWriter writer = new FileWriter(correctionPath);
- String[] words;
- while(scanFile.hasNext()){
- words = takeWords(scanFile.nextLine());
- if(words[0].equals(oldNumber)){
- writer.write(newTrain.ticketsNumber + " " + newTrain.townName + ' ' + newTrain.time + ' ' + newTrain.ticketsNumber +'\n');
- }
- else{
- writer.write(words[0] +' '+ words[1] +' '+ words[2] +' '+ words[3] +'\n');
- }
- }
- scanFile.close();
- writer.close();
- }
- static void deleteLine(String number, String dataPath, String correctionPath) throws IOException{
- Scanner scanFile = new Scanner(new File(dataPath));
- BufferedWriter writer = new BufferedWriter(new FileWriter(correctionPath));
- String[] words;
- while(scanFile.hasNext()){
- words = takeWords(scanFile.nextLine());
- if(!number.equals(words[0])){
- writer.write(words[0]+' '+words[1]+' '+words[2]+' '+words[3]+'\n');
- }
- }
- writer.close();
- scanFile.close();
- }
- static void addRecordToFile(String path){
- String trainNumber, townName, leaveTime, ticketsNumber;
- System.out.print("Введите номер состава: ");
- trainNumber = takeTrainNumber();
- System.out.print("Введите название города прибытия: ");
- townName = takeTownName();
- System.out.print("Введите время отъезда/прибытия: ");
- leaveTime = takeTime();
- System.out.print("Введите количество билетов на поезд: ");
- ticketsNumber = takeTickets();
- writeToFile(path, trainNumber,townName,leaveTime,ticketsNumber);
- System.out.println("Изменения успешно внесены!");
- }
- static void changeRecordInFile(String path, String correctionPath) throws IOException{
- String oldNumber, line;
- byte choice;
- System.out.print("Введите номер состава, информацию о котором хотите изменить: ");
- oldNumber = takeOldNumber(path);
- line = takeChangeLine(oldNumber, path);
- String[] words = takeWords(line);
- System.out.println("1.Изменить номер состава\n2.Оставить");
- choice = takeStartChoice();
- if(choice == chooseFileConst){
- System.out.println("Введите номер нового состава:");
- String trainNumber = takeTrainNumber();
- words[0] = trainNumber;
- }
- System.out.println("1.Изменить город назначения\n2.Оставить");
- choice = takeStartChoice();
- if(choice == chooseFileConst){
- System.out.println("Введите новый город назначения:");
- String townName = takeTownName();
- words[1] = townName;
- }
- System.out.println("1.Изменить время отъезда/прибытия\n2.Оставить");
- choice = takeStartChoice();
- if(choice == chooseFileConst){
- System.out.println("Введите новое время отъезда/прибытия:");
- String leaveTime = takeTime();
- words[2] = leaveTime;
- }
- System.out.println("1.Изменить количество билетов\n2.Оставить");
- choice = takeStartChoice();
- if(choice == chooseFileConst){
- System.out.println("Введите новое количество билетов:");
- String tickets = takeTickets();
- words[3] = tickets;
- }
- trainInfo newTrain = new trainInfo(words[0], words[1], words[2], Integer.parseInt(words[3]));
- changeRecord(newTrain, oldNumber, path, correctionPath);
- System.out.println("Изменения успешно внесены!");
- }
- static void deleteRecordInFile(String dataPath, String correctionPath) throws IOException{
- System.out.print("Введите номер состава, информацию о котором хотите удалить: ");
- String trainNumber = takeOldNumber(dataPath);
- deleteLine(trainNumber, dataPath, correctionPath);
- System.out.print("Изменения успешно сохранены!");
- }
- static void showRecordsFromFile(String path) throws FileNotFoundException{
- System.out.println("Расписание поездов:");
- Scanner scanFile = new Scanner(new File(path));
- while(scanFile.hasNext())
- System.out.println(scanFile.nextLine());
- scanFile.close();
- }
- public static void main(String[] args) throws IOException{
- System.out.println("Данная программа позволяет взаимодействовать с расписанием поездов\n1.Выбрать файл\n2.Выйти");
- byte choiceVar = takeStartChoice();
- String dataFilePath, correctionFilePath;
- if (choiceVar == chooseFileConst){
- System.out.println("Введите путь к файлу с данными:");
- dataFilePath = takeDataFile();
- System.out.println("Выберите одну из опций.\n1.Добавить сведения\n2.Изменить сведения\n3.Удалить сведения\n4.Показать сведения");
- choiceVar = takeMainChoice();
- if(choiceVar == chooseAddConst){
- addRecordToFile(dataFilePath);
- }
- else if(choiceVar == chooseChangeConst){
- System.out.println("Введите путь к файлу корректюр:");
- correctionFilePath = takeFilePath();
- changeRecordInFile(dataFilePath, correctionFilePath);
- }
- else if(choiceVar == chooseDeleteConst){
- System.out.println("Введите путь к файлу корректюр:");
- correctionFilePath = takeFilePath();
- deleteRecordInFile(dataFilePath,correctionFilePath);
- }
- else if(choiceVar == chooseShowConst){
- showRecordsFromFile(dataFilePath);
- }
- }
- scan.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement