/
teuwers
/
counter
Обзор
Документация
Войти
/
teuwers
/
counter
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/CounterApp.java
70 строк
2 KB
Mikhail Chernobrov
Logical edits
07 мар 2025, 00:30
07 мар 2025, 00:30
21e155d
Код
Авторство
О чём код?
import java.io.*; import java.util.Scanner; public class CounterApp { private static final String FILENAME = "counter.ser"; private Counter counter; CounterApp() throws IOException, ClassNotFoundException { try { FileInputStream fileInputStream = new FileInputStream(FILENAME); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); this.counter = (Counter) objectInputStream.readObject(); objectInputStream.close(); System.out.println("Счетчик загружен, значение: " + this.counter.getCount()); } catch (FileNotFoundException e) { this.counter = new Counter(); saveCounterState(); System.out.println("Счетчик создан, значение: " + this.counter.getCount()); } } private void increase() throws IOException, ClassNotFoundException { this.counter.setCount(this.counter.getCount() + 1); saveCounterState(); System.out.println("Счётчик увеличен.\n" + this.counter); } private void reset() throws IOException, ClassNotFoundException { this.counter.setCount(0); saveCounterState(); System.out.println("Счётчик сброшен.\n" + this.counter); } private void stop() throws IOException, ClassNotFoundException { this.saveCounterState(); System.out.println(this.counter + "\nЗавершаю работу."); } public void run() throws IOException, ClassNotFoundException { Scanner input = new Scanner(System.in); String command; do { System.out.print("Введите команду: "); command = input.nextLine(); if (command.equals("/inc")) { this.increase(); } else if (command.equals("/reset")) { this.reset(); } else if (command.equals("/stop")) { this.stop(); break; } else { System.out.println("Неизвестная команда."); } } while(true); } private void saveCounterState() throws IOException, ClassNotFoundException { FileOutputStream fileOutputStream = new FileOutputStream(FILENAME); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(this.counter); objectOutputStream.close(); } }