Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Scanner;
- class Participant {
- String surname;
- int points;
- Participant(String surname, int points) {
- this.surname = surname;
- this.points = points;
- }
- }
- public class Main {
- static void sort(ArrayList<Participant> participants) {
- for(int i = 0; i < participants.size(); i++) {
- Participant participant = participants.get(i);
- int maxIdx = i;
- for(int j = i + 1; j < participants.size(); j++) {
- int points = participants.get(j).points;
- int maxPoints = participants.get(maxIdx).points;
- if(points == maxPoints) {
- String surname = participants.get(j).surname;
- String maxSurname = participants.get(maxIdx).surname;
- int result = surname.compareToIgnoreCase(maxSurname);
- if(result < 0)
- maxIdx = j;
- } else if(points > maxPoints)
- maxIdx = j;
- }
- if(maxIdx != i) {
- participants.set(i, participants.get(maxIdx));
- participants.set(maxIdx, participant);
- }
- }
- }
- static boolean greeting(Scanner scan) {
- System.out.println("Данная программа сортирует участников соревнования по убыванию количества баллов\n");
- System.out.println("Введите [C], если хотите ввести файл с консоли, или [F], если хотите сделать ввод из файла");
- boolean notCorrect = true;
- String inputFrom = scan.nextLine().toLowerCase();
- while (notCorrect) {
- if(inputFrom.equals("f") || inputFrom.equals("c"))
- notCorrect = false;
- else {
- System.out.println("Вы должны ввести либо [C], либо [F]");
- inputFrom = scan.nextLine().toLowerCase();
- }
- }
- return inputFrom.equals("f");
- }
- static ArrayList<Participant> readFile(String filePath) {
- ArrayList<Participant> participants = new ArrayList<>();
- try(FileReader fr = new FileReader(filePath)) {
- Scanner frScan = new Scanner(fr);
- while (frScan.hasNext()) {
- String str = frScan.nextLine();
- String[] data = str.split("\\s+");
- String surname = data[0];
- int points = Integer.parseInt(data[1]);
- participants.add(new Participant(surname, points));
- }
- } catch (IOException err) {
- System.out.println("Произошла ошибка при чтении файла. Убедитесь, что такой файл существует, либо проверьте имя файла");
- }
- return participants;
- }
- static void saveResult(ArrayList<Participant> participants, Scanner scan) {
- System.out.println("Хотите сохранить результат в файл? [Д/Н]");
- String choice = scan.nextLine().toLowerCase();
- boolean notCorrect = true;
- while (notCorrect) {
- if(choice.equals("д") || choice.equals("н"))
- notCorrect = false;
- else {
- System.out.println("Вы должны ввести либо [Д], либо [Н]");
- choice = scan.nextLine().toLowerCase();
- }
- }
- boolean saveToFile = choice.equals("д");
- if(saveToFile) {
- try (FileWriter fw = new FileWriter("output.txt", false)) {
- for (Participant participant : participants) {
- String str = participant.surname + " " + participant.points + '\n';
- fw.write(str);
- }
- System.out.println("Результат был сохранен в файл output.txt");
- } catch (IOException err) {
- System.out.println("Произошла ошибка при попытке записи результата в файл");
- }
- }
- }
- static void showResult(ArrayList<Participant> participants) {
- System.out.println("Результат:");
- for(Participant participant : participants)
- System.out.println(participant.surname + " " + participant.points);
- }
- static ArrayList<Participant> inputParticipants(Scanner scan, boolean fromFile) {
- ArrayList<Participant> participants = new ArrayList<>();
- if(fromFile) {
- System.out.println("Введите путь к файлу");
- String filePath = scan.nextLine();
- participants = readFile(filePath);
- } else {
- System.out.println("Введите фамилию участника и набранные им баллы");
- boolean continueCycle = true;
- while(continueCycle) {
- System.out.println("Введите фамилию участника, либо stop, чтобы прекратить ввод");
- String surname = scan.nextLine();
- if(surname.equals("stop"))
- continueCycle = false;
- else
- try {
- System.out.println("Введите количество баллов");
- int points = Integer.parseInt(scan.nextLine());
- participants.add(new Participant(surname, points));
- } catch (Exception err) {
- System.out.println("Количество баллов должно быть числом, повторите ввод, начиная с фамилии студента");
- }
- }
- }
- return participants;
- }
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- boolean inputFromFile = greeting(scan);
- ArrayList<Participant> participants = inputParticipants(scan, inputFromFile);
- sort(participants);
- showResult(participants);
- saveResult(participants, scan);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement