Я использую HashMap для хранения строки, за которой следует объект Doctor, где строка — это копия кода в Doctor.
Сначала я подумал, что это просто проблема с проверкой состояния и выдачей исключения, но это не так.
Во-вторых, я распечатал всех добавленных врачей, но все предыдущие врачи были такими же, как и новые. >
public class Main {
public static void main(String[] args) {
DoctorController controler = new DoctorController();
try {
controler.addWorker();
controler.addWorker();
controler.displayAll();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Это та часть, где возникает проблема:
public class DoctorController {
private final DoctorInputer inputer;
private final DoctorManagement management;
public DoctorController() {
management = new DoctorManagement();
inputer = new DoctorInputer();
}
public void addWorker() throws Exception {
Doctor doctor = inputer.getDoctorDetails();
if (management.addDoctor(doctor)) {
System.out.println("Add successful");
} else {
System.out.println("Can not add doctor!");
}
}
public void displayAll() {
management.displayAll();
}
}
import java.util.HashMap;
public class DoctorManagement {
private final HashMap doctors;
public DoctorManagement() {
doctors = new HashMap();
}
public boolean addDoctor(Doctor d) throws Exception {
if (doctors.containsKey(d.getCode())) {
throw new Exception("Doctor code " + d.getCode() + " is duplicate");
}
if (d == null) {
throw new Exception("Data does not exist");
}
doctors.put(d.getCode(), d);
return true;
}
//Method: Displat All the doctor
}
Эти части — всего лишь ВВОД, но, возможно, они вам понадобятся
public class DoctorInputer {
private final Doctor doctor;
public DoctorInputer() {
doctor = new Doctor();
}
public Doctor getDoctorDetails() {
doctor.setCode(Validation.getString("Enter code: ",
"Code should follow format 'DOC_number'",
"^DOC\\d+$"));
doctor.setName(Validation.getString("Enter name: ",
"Invalid",
"[a-zA-Z]+"));
doctor.setSpecialization(Validation.getString("Enter specialization: ",
"Invalid",
"[a-zA-Z]+"));
doctor.setAvaiability(Validation.getInt("Enter avaiability: ",
"Avaiability >= 0",
"Invalid", 0, Integer.MAX_VALUE));
return doctor;
}
}
public class Doctor {
private String code;
private String name;
private String specialization;
private int avaiability;
// Getter and Setters
@Override
public String toString(){
return String.format("%-6s %-10s %-12s %-2d", code, name, specialization, avaiability);
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... e-whenever
Мой HashMap, содержащий новый Doctor, продолжает переопределять предыдущий всякий раз, когда я использую метод addDoctor ⇐ JAVA
Программисты JAVA общаются здесь
1719734241
Anonymous
Я использую HashMap для хранения строки, за которой следует объект Doctor, где строка — это копия кода в Doctor.
Сначала я подумал, что это просто проблема с проверкой состояния и выдачей исключения, но это не так.
Во-вторых, я распечатал всех добавленных врачей, но все предыдущие врачи были такими же, как и новые. >
public class Main {
public static void main(String[] args) {
DoctorController controler = new DoctorController();
try {
controler.addWorker();
controler.addWorker();
controler.displayAll();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Это та часть, где возникает проблема:
public class DoctorController {
private final DoctorInputer inputer;
private final DoctorManagement management;
public DoctorController() {
management = new DoctorManagement();
inputer = new DoctorInputer();
}
public void addWorker() throws Exception {
Doctor doctor = inputer.getDoctorDetails();
if (management.addDoctor(doctor)) {
System.out.println("Add successful");
} else {
System.out.println("Can not add doctor!");
}
}
public void displayAll() {
management.displayAll();
}
}
import java.util.HashMap;
public class DoctorManagement {
private final HashMap doctors;
public DoctorManagement() {
doctors = new HashMap();
}
public boolean addDoctor(Doctor d) throws Exception {
if (doctors.containsKey(d.getCode())) {
throw new Exception("Doctor code " + d.getCode() + " is duplicate");
}
if (d == null) {
throw new Exception("Data does not exist");
}
doctors.put(d.getCode(), d);
return true;
}
//Method: Displat All the doctor
}
Эти части — всего лишь [b]ВВОД[/b], но, возможно, они вам понадобятся
public class DoctorInputer {
private final Doctor doctor;
public DoctorInputer() {
doctor = new Doctor();
}
public Doctor getDoctorDetails() {
doctor.setCode(Validation.getString("Enter code: ",
"Code should follow format 'DOC_number'",
"^DOC\\d+$"));
doctor.setName(Validation.getString("Enter name: ",
"Invalid",
"[a-zA-Z]+"));
doctor.setSpecialization(Validation.getString("Enter specialization: ",
"Invalid",
"[a-zA-Z]+"));
doctor.setAvaiability(Validation.getInt("Enter avaiability: ",
"Avaiability >= 0",
"Invalid", 0, Integer.MAX_VALUE));
return doctor;
}
}
public class Doctor {
private String code;
private String name;
private String specialization;
private int avaiability;
// Getter and Setters
@Override
public String toString(){
return String.format("%-6s %-10s %-12s %-2d", code, name, specialization, avaiability);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78687666/my-hashmap-which-contains-new-doctor-keeps-overriding-the-previous-one-whenever[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия