Я студент и недавно изучаю темы. Что я пытаюсь сделать, так это реализовать шаблон MVC, который управляет такими функциями, как начало подсчета, остановка подсчета, обратный подсчет и т.д. c ...
Моя конечная цель состоит в том, что мне нужно получить пользовательский ввод, пока счетчик отсчитывает от 1, и если я ввожу 2 (при условии, что опция 2 останавливает счетчик), счетчик должен прекратить подсчет.
Например:
Counting...
1
2
3
(If I press 2 here)
Counter stopped running!
Поскольку это домашнее задание из моего колледжа, я не могу загрузить сюда реализованный мной код.
Я сделал,
MVC шаблон:
Класс контроллера = получает модель и представление с помощью конструктора контроллера. Этот класс также предоставляет метод service (), который использует регистр переключателя, чтобы заставить пользователя вводить параметры для запуска функции подсчета (например, case1: startCounting () case2: stopCounting () и et c ...)
View class = предоставляет параметры с использованием функции System.out.println и displayMenu ().
Model class = реализует такие функции, как startCounting (), stopCounting и др. c ...
Теперь мне нужно добавить потоки для этой реализации, чтобы взаимодействовать с пользовательским вводом с этим процессом подсчета.
Могу я получить какие-нибудь подсказки? Например, какой класс следует расширить для потока и каким образом следует реализовать метод run ()?
Код скелета:
Класс CountController
public class CounterController {
private Counter model;
private CounterView view;
public CounterController(Counter model, CounterView view) {
this.model = model;
this.view = view;
}
}
Класс модели
public class Counter {
private int count = 0;
private boolean counting = false;
private Integer ceiling = null;
private Integer floor = null;
private boolean reverse = false;
public void startCounting() {
counting = true;
while (counting && checkLimits()) {
try {
Thread.sleep(1000);
count = reverse ? count - 1 : count + 1;
// You should replace this print with something observable so the View can handle it
System.err.println(count);
} catch (InterruptedException ignored) {}
}
}
public void stopCounting() {
counting = false;
}
public void setReverse(boolean reverse) {
this.reverse = reverse;
}
public void setCeiling(Integer ceiling) {
this.ceiling = ceiling;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public int getCount() {
return count;
}
public void resetCount() {
count = 0;
}
private boolean checkLimits() {
if (null != ceiling && count >= ceiling) {
return false;
}
if (null != floor && count <= floor) {
return false;
}
return true;
}
}
Класс просмотра
public class CounterView {
private Counter model;
public CounterView(Counter model) {
this.model = model;
}
public void launch() {
}
}
Просмотр до класса
class ViewUtils {
static int displayMenu(String header, String[] options, String prompt) {
System.out.println("\n" + header);
for (int i = 0; i < options.length; i++) {
System.out.println((i+1) + ". " + options[i]);
}
while (true) {
Integer response = getInt(prompt, true);
int selection = response != null ? response : -1;
if (selection > 0 && selection <= options.length) {
return selection;
} else {
System.out.println("Invalid menu selection");
}
}
}
static String getString(String prompt, boolean allowBlank) {
Scanner s = new Scanner(System.in);
String response;
do {
System.out.println(prompt);
response = s.nextLine();
if (!allowBlank && "".equals(response)) {
response = null;
System.out.println("Blank entry is not allowed here.");
}
} while (null == response);
return response;
}
static Integer getInt(String prompt, boolean allowBlank) {
int response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
try {
response = Integer.parseInt(str);
return response;
} catch (NumberFormatException e) {
System.out.println("Invalid input - number required");
}
} while (true);
}
static Boolean getBoolean(String prompt, boolean allowBlank) {
prompt = prompt + "(y/n) ";
Boolean response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
if ("y".equals(str.toLowerCase())) {
return true;
}
if ("n".equals((str.toLowerCase()))) {
return false;
}
System.out.println("Invalid input - must be y or n");
} while (true);
}
}
Основной класс
public class MainDriver {
public static void main(String[] args) {
Counter model = new Counter();
CounterView view = new CounterView(model);
CounterController controller = new CounterController(model, view);
controller.service();
}
}