Advertisement
Alyks

Untitled

Mar 1st, 2020
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.36 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.FileReader;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.Scanner;
  8.  
  9. class Participant {
  10.     String surname;
  11.     int points;
  12.     Participant(String surname, int points) {
  13.         this.surname = surname;
  14.         this.points = points;
  15.     }
  16. }
  17.  
  18. public class Main {
  19.     static void sort(ArrayList<Participant> participants) {
  20.         for(int i = 0; i < participants.size(); i++) {
  21.             Participant participant = participants.get(i);
  22.             int maxIdx = i;
  23.             for(int j = i + 1; j < participants.size(); j++) {
  24.                 int points = participants.get(j).points;
  25.                 int maxPoints = participants.get(maxIdx).points;
  26.                 if(points == maxPoints) {
  27.                     String surname = participants.get(j).surname;
  28.                     String maxSurname = participants.get(maxIdx).surname;
  29.                     int result = surname.compareToIgnoreCase(maxSurname);
  30.                     if(result < 0)
  31.                         maxIdx = j;
  32.                 } else if(points > maxPoints)
  33.                     maxIdx = j;
  34.             }
  35.  
  36.             if(maxIdx != i) {
  37.                 participants.set(i, participants.get(maxIdx));
  38.                 participants.set(maxIdx, participant);
  39.             }
  40.         }
  41.     }
  42.  
  43.     static boolean greeting(Scanner scan) {
  44.         System.out.println("Данная программа сортирует участников соревнования по убыванию количества баллов\n");
  45.         System.out.println("Введите [C], если хотите ввести файл с консоли, или [F], если хотите сделать ввод из файла");
  46.         boolean notCorrect = true;
  47.         String inputFrom = scan.nextLine().toLowerCase();
  48.         while (notCorrect) {
  49.             if(inputFrom.equals("f") || inputFrom.equals("c"))
  50.                 notCorrect = false;
  51.             else {
  52.                 System.out.println("Вы должны ввести либо [C], либо [F]");
  53.                 inputFrom = scan.nextLine().toLowerCase();
  54.             }
  55.         }
  56.  
  57.         return inputFrom.equals("f");
  58.     }
  59.  
  60.     static ArrayList<Participant> readFile(String filePath) {
  61.         ArrayList<Participant> participants = new ArrayList<>();
  62.         try(FileReader fr = new FileReader(filePath)) {
  63.             Scanner frScan = new Scanner(fr);
  64.             while (frScan.hasNext()) {
  65.                 String str = frScan.nextLine();
  66.                 String[] data = str.split("\\s+");
  67.                 String surname = data[0];
  68.                 int points = Integer.parseInt(data[1]);
  69.                 participants.add(new Participant(surname, points));
  70.             }
  71.         } catch (IOException err) {
  72.             System.out.println("Произошла ошибка при чтении файла. Убедитесь, что такой файл существует, либо проверьте имя файла");
  73.         }
  74.         return participants;
  75.     }
  76.  
  77.     static void saveResult(ArrayList<Participant> participants, Scanner scan) {
  78.         System.out.println("Хотите сохранить результат в файл? [Д/Н]");
  79.         String choice = scan.nextLine().toLowerCase();
  80.         boolean notCorrect = true;
  81.         while (notCorrect) {
  82.             if(choice.equals("д") || choice.equals("н"))
  83.                 notCorrect = false;
  84.             else {
  85.                 System.out.println("Вы должны ввести либо [Д], либо [Н]");
  86.                 choice = scan.nextLine().toLowerCase();
  87.             }
  88.         }
  89.         boolean saveToFile = choice.equals("д");
  90.         if(saveToFile) {
  91.             try (FileWriter fw = new FileWriter("output.txt", false)) {
  92.                 for (Participant participant : participants) {
  93.                     String str = participant.surname + " " + participant.points + '\n';
  94.                     fw.write(str);
  95.                 }
  96.                 System.out.println("Результат был сохранен в файл output.txt");
  97.             } catch (IOException err) {
  98.                 System.out.println("Произошла ошибка при попытке записи результата в файл");
  99.             }
  100.         }
  101.     }
  102.  
  103.     static void showResult(ArrayList<Participant> participants) {
  104.         System.out.println("Результат:");
  105.         for(Participant participant : participants)
  106.             System.out.println(participant.surname + " " + participant.points);
  107.     }
  108.  
  109.     static ArrayList<Participant> inputParticipants(Scanner scan, boolean fromFile) {
  110.         ArrayList<Participant> participants = new ArrayList<>();
  111.         if(fromFile) {
  112.             System.out.println("Введите путь к файлу");
  113.             String filePath = scan.nextLine();
  114.             participants = readFile(filePath);
  115.         } else {
  116.             System.out.println("Введите фамилию участника и набранные им баллы");
  117.             boolean continueCycle = true;
  118.             while(continueCycle) {
  119.                 System.out.println("Введите фамилию участника, либо stop, чтобы прекратить ввод");
  120.                 String surname = scan.nextLine();
  121.                 if(surname.equals("stop"))
  122.                     continueCycle = false;
  123.                 else
  124.                     try {
  125.                         System.out.println("Введите количество баллов");
  126.                         int points = Integer.parseInt(scan.nextLine());
  127.                         participants.add(new Participant(surname, points));
  128.                     } catch (Exception err) {
  129.                         System.out.println("Количество баллов должно быть числом, повторите ввод, начиная с фамилии студента");
  130.                     }
  131.             }
  132.         }
  133.         return participants;
  134.     }
  135.  
  136.     public static void main(String[] args) {
  137.         Scanner scan = new Scanner(System.in);
  138.         boolean inputFromFile = greeting(scan);
  139.         ArrayList<Participant> participants = inputParticipants(scan, inputFromFile);
  140.         sort(participants);
  141.         showResult(participants);
  142.         saveResult(participants, scan);
  143.     }
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement