/
alex_ep0411
/
java_lab1
Обзор
Документация
Войти
/
alex_ep0411
/
java_lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/controller/ConverterController.java
165 строк
6 KB
александр
лабораторная работа 2
08 июн 2026, 13:14
08 июн 2026, 13:14
a6f4df3
Код
Авторство
О чём код?
package controller; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import model.ConverterModel; import model.InputValidator; import model.MeetingPlanner; import java.net.URL; import java.util.ResourceBundle; public class ConverterController implements Initializable { @FXML private TextField timeField; @FXML private ComboBox<String> fromZone; @FXML private ComboBox<String> toZone; @FXML private Label convertResult; @FXML private Label differenceResult; @FXML private TextField meetingHour; @FXML private ComboBox<String> organizerZone; @FXML private TextField participantName; @FXML private ComboBox<String> participantZone; @FXML private TextArea meetingResult; @FXML private Label errorLabel; private ConverterModel model; @Override public void initialize(URL location, ResourceBundle resources) { model = new ConverterModel(); // Заполняем списки часовых поясов String[] zones = {"MSK", "UTC", "EST"}; fromZone.getItems().addAll(zones); toZone.getItems().addAll(zones); organizerZone.getItems().addAll(zones); participantZone.getItems().addAll(zones); // Значения по умолчанию fromZone.setValue("MSK"); toZone.setValue("UTC"); organizerZone.setValue("MSK"); participantZone.setValue("EST"); participantName.setText("Коллега"); errorLabel.setText(""); } // Конвертация времени @FXML private void handleConvert() { errorLabel.setText(""); String input = timeField.getText(); // Валидация if (InputValidator.isEmpty(input)) { errorLabel.setText("Ошибка: введите время"); return; } if (!InputValidator.isNumeric(input)) { errorLabel.setText("Ошибка: введите число (например, 14.5)"); return; } if (!InputValidator.isPositive(input)) { errorLabel.setText("Ошибка: время должно быть больше 0"); return; } if (!InputValidator.isWithinMax(input, 24)) { errorLabel.setText("Ошибка: время не может превышать 24 часа"); return; } double hours = Double.parseDouble(input); String from = fromZone.getValue(); String to = toZone.getValue(); double result = model.convert(hours, from, to); // Нормализуем результат в диапазон 0-24 double normalized = result % 24; if (normalized < 0) normalized += 24; convertResult.setText(String.format("%.2f %s = %.2f %s", hours, from, normalized, to)); int diff = model.getTimeDifference(from, to); String diffSign = diff >= 0 ? "+" : ""; differenceResult.setText(String.format("Разница: %s%d часов", diffSign, diff)); } // Планирование встречи @FXML private void planMeeting() { errorLabel.setText(""); String hourStr = meetingHour.getText(); // Валидация if (InputValidator.isEmpty(hourStr)) { errorLabel.setText("Ошибка: введите час встречи"); return; } if (!InputValidator.isNumeric(hourStr)) { errorLabel.setText("Ошибка: введите число (час от 0 до 23)"); return; } int hour = Integer.parseInt(hourStr); if (hour < 0 || hour > 23) { errorLabel.setText("Ошибка: час должен быть от 0 до 23"); return; } String orgZone = organizerZone.getValue(); String partZone = participantZone.getValue(); String partName = participantName.getText(); if (InputValidator.isEmpty(partName)) { partName = "Участник"; } // Рассчитываем время участника int participantHour = MeetingPlanner.getParticipantTime(hour, orgZone, partZone); // Проверяем удобство для обоих boolean organizerOk = MeetingPlanner.isConvenient(hour); boolean participantOk = MeetingPlanner.isConvenient(participantHour); // Формируем результат StringBuilder result = new StringBuilder(); result.append("=== Планирование встречи ===\n\n"); result.append(String.format("Вы (пояс %s): %d:00 - %s\n", orgZone, hour, MeetingPlanner.getRecommendation(hour))); result.append(String.format("%s (пояс %s): %d:00 - %s\n\n", partName, partZone, participantHour, MeetingPlanner.getRecommendation(participantHour))); if (organizerOk && participantOk) { result.append("✅ Отлично! Время удобно для всех!\n"); result.append("🎉 Можно назначать встречу!"); } else { result.append("⚠️ Внимание! Время неудобно для некоторых участников.\n\n"); result.append("💡 Рекомендации:\n"); // Предлагаем альтернативы boolean foundAlternative = false; for (int altHour = 9; altHour <= 17; altHour++) { int altParticipantHour = MeetingPlanner.getParticipantTime(altHour, orgZone, partZone); if (MeetingPlanner.isConvenient(altHour) && MeetingPlanner.isConvenient(altParticipantHour)) { result.append(String.format(" • Попробуйте %d:00 (по вашему времени)\n", altHour)); foundAlternative = true; if (foundAlternative) break; // Показываем только первую альтернативу } } if (!foundAlternative) { result.append(" • К сожалению, не найдено удобного времени\n"); result.append(" • Попробуйте выбрать другой день\n"); } } meetingResult.setText(result.toString()); } }