Java Concert Hall OOP design - java

I want to make a Booking class to book concert tickets. A ConcertHall class has 2 different seats, namely VIP and Regular. I've chosen Seat[][] as my data structure, where a Seat class contains seat_number:String and preference:String. Now, the VIP and Regular seats have a different capacity. Let's say the VIP's capacity is 10x5 seats and the Regular's capacity is 50x100 seats. The seats corresponding to both VIP and Regular also have Left, Center, and Right preferences.
The problem with my current design is I have so many redundant code . Let's say a user wants to book a concert ticket, he/she will call the method: book("VIP", "Mary", "Center"). This is what my design and book method look like:
class Booking
{
private ConcertHall A;
public Booking(String name)
{
A = new ConcertHall(name);
}
public boolean book(String serviceClass, String name, String preference)
{
Seat seat = find(serviceClass, preference)
if(seat != null)
{
assignSeat(seat, name);
return true;
}
return false;
}
}
class ConcertHall
{
private Seat[][] VIP;
private Seat[][] Regular;
public Seat findSeat(String serviceClass, String preference)
{
if(serviceClass.equals("VIP"))
{
// query VIP array
}
else if(serviceClass.equals("Regular"))
{
// query Regular array
}
}
public boolean assignSeat(Seat seat, String name)
{
if(serviceClass.equals("VIP"))
{
// query VIP array
}
else if(serviceClass.equals("Regular"))
{
// query Regular array
}
}
}
There's already a problem here, namely for almost every method in ConcertHall, I have to do 2 identical checking for the VIP class and Regular class. Now I'm stuck. My code looks long and stupid because of the 2 identical checking.
===================================update===================================
I forgot to mention, there's an additional requirement. I have to keep track of the seats' position. Let's say a group of people want to book concert tickets, we have to find available seats in the same row. So, a HashMap wouldn't work here I think.

Factor out the identical array checking code into a method of its own and then pass it the correct lookup array. Something like
public Seat findSeat(String serviceClass, String preference)
{
if(serviceClass.equals("VIP"))
{
return findSeatIn(VIP, preference);
}
else if(serviceClass.equals("Regular"))
{
return findSeatIn(Regular, preference);
}
}
public Seat findSeatIn(Seat[][] seatArray, String preference)
{
// query seatArray for preference
}
Then repeat this with assignSeat() and assignSeatIn().
Also, findSeat() should ideally be findSeats() returning a list of seats matching a user's preference. The user should then be a able to choose one s/he likes the most, which should then be assigned by assignSeat(). Just a thought.

You can have a Map in your ConcertHall. In your check just do a get on map, query and assign. So you can do something like this
class ConcertHall{
private Map<String, Seat[][]> seatMap;
public Seat findSeat(String serviceClass, String preference){
Seat[][] seats = seatMap.get(serviceClass);
//query on seats
}
To use this, you need to put the seats in map appropriately. moreover you can use enum for the values like VIP and Regular

It seems to me that there is room (if I may say so) for an additional class that would represent individual regions of the hall; say:
class Zone {
Seat[][] seats;
public Zone(int rows, int columns) {
seats = new Seat[rows][columns];
}
public Seat findSeat(String preference) {
...
}
public boolean assignSeat(Seat seat, String name) {
...
}
}
This class could be sub-classed if different service classes would required a different behavior.
The ConcertHall class could be simpler:
class ConcertHall{
private Map<String, Zone> zoneMap = new HashMap<String, Zone>();
{
zoneMap.put("VIP", new Zone(5,10));
zoneMap.put("Regular", new Zone(50,100));
}
public Seat findSeat(String serviceClass, String preference) {
return zoneMap.get(serviceClass).findSeat(preference);
}
...
}

You need a good initial design in order to get anywhere with oop. Here is an alternate implementation you might want to consider:
class Booking {
public Booking(String personName, Seat seat) {
...
}
// getter and setters...blah blah
}
class ConcertHall {
// Making it protected allows for easy subclassing
protected List<Booking> vipSeating;
protected List<Booking> regularSeating;
public ConcertHall(String name, int capVip, int capReg) {
vip = new ArrayList<>();
regular = new ArrayList<>();
// initialise capacity, etc
}
public void addVipBooking(Booking b) throws ArrayIndexOutOfBoundsException {
// If there is room, add the person, else throw an exception
}
public void addRegularBooking(Booking b) throws ArrayIndexOutOfBoundsException {
// If there is room, add the person, else throw an exception
}
public boolean vipIsFull() {
// is the vip section full??
}
public boolean regularIsFull() {
// is the regular section full??
}
}

Related

deleting duplicates from array list

I'm creating a simple RPG console game, I'm at the stage of creating an inventory and loot system. Present in the program, both class Player and class Monster have the arrayList Backpack properties, when the program creates an object of the monster class, items in the monster's backpack are also automatically created, after killing the monster, you can take them to your backpack, and this is where my problem begins how to elegantly prevent duplication of items in the backpack, each item is a class too, now this function works by checking in a nested loop each item one by one to see if it is already in the backpack if it is instead of adding it once moreover, it increases its amount property, if I don't have this item in my backpack, it just adds to the list, the solution works, but definitely it is not the right solution, because with many of items this checking mechanism will grow a lot, if anyone has any valuable tips I will be grateful.
I also have a second idea to create a boolean Is_it_in_Backpack variable, and somehow connect it with the loot collecting mechanism
Below some code sample
public class Player {
public static ArrayList<Item> Backpack = new ArrayList<>()
}
and the class Skieleton:
public class Skieleton extends Monsters {
public static ArrayList<Item> Backpack;
public Skieleton() {
Backpack = new ArrayList<>();
Backpack.add(new Weapon("Rusty sword", "Just a rusty sword", 3, 2 ));
Backpack.add(new Armor("Leather Armor", "Old leather armor", 6, 3));
}
class item:
public class Item {
public String ItemName;
public String Description;
public int ItemSize;
public int ItemWeight;
public int Amount;
public Item(String ItemName, String Description, int ItemSize, int ItemWeight)
{
this.ItemName = ItemName;
this.Description = Description;
this.ItemSize = ItemSize;
this.ItemWeight = ItemWeight;
}
public Item() {
}
}
I recommend you use a class that extends java.util.Set:
If order is not important for you, you can use HashSet;
If order of insertion is important, you can use LinkedHashSet;
If natural order is important (alphabetical by name or other property), you can use TreeSet and implement the interface Comparable onto the class inserted in the collection.
However, regardless of your choice, it's recommended you implement hashCode() (for optimization) and equals() (to let collection identify which item is equal to other and avoid duplication).
If you can use third party libraries, I'd recommend using a Bag from Eclipse Collections.
With your Item class implementing equals and hashCode on ItemName field, your example usage could look like:
final MutableBag<Item> backPack = new HashBag<>();
final Item rustySword = new Item("Rusty sword", "Just a rusty sword", 3, 2);
final Item leatherArmour = new Item("Leather Armor", "Old leather armor", 6, 3);
backPack.add(rustySword);
backPack.add(leatherArmour);
backPack.add(rustySword);
System.out.println(backPack.toMapOfItemToCount()); // prints {Item[ItemName='Rusty sword']=2, Item[ItemName='Leather Armor']=1}
System.out.println(backPack.occurrencesOf(rustySword)); // prints 2
The API is rich, and provides a lot more:
https://www.eclipse.org/collections/javadoc/11.0.0/org/eclipse/collections/api/bag/Bag.html
I would use a Map.
Here's my suggestion:
import java.util.*;
class Player {
public Backpack backpack= new Backpack();
}
class Monster { }
class Skieleton extends Monster {
public Backpack backpack= new Backpack();
public Skieleton() {
backpack.add(new Weapon("Rusty sword", "Just a rusty sword", 3, 2 ));
backpack.add(new Armor("Leather Armor", "Old leather armor", 6, 3));
}
}
class Backpack {
private HashMap<Item,Item> items = new HashMap<>();
public Item add(Item item){
if (items.containsKey(item)){
items.get(item).Amount=+ item.Amount;
return items.get(item);
} else {
items.put(item,item);
return item;
}
}
public Item get(Item item){
return items.getOrDefault(item, null);
}
}
class Item {
public String ItemName;
public String Description;
public int ItemSize;
public int ItemWeight;
public int Amount;
public Item(String ItemName, String Description, int ItemSize, int ItemWeight)
{
this.ItemName = ItemName;
this.Description = Description;
this.ItemSize = ItemSize;
this.ItemWeight = ItemWeight;
}
public Item() {
}
public boolean equals(Object o){
if (o instanceof Item){
return ItemName.equals( ((Item)o).ItemName);
}
return false;
}
}
You can use a HashMap for storing the items. First, I would like to change the Item class to not have amount field in it. Let an item denote what an item is (name, description, size and weight).
Here's the updated backpack:
Map<Item, Integer> backpack = new HashMap<>();
To add an item, you can use Map#merge method.
public void addItemToBackpack(Item item, int quantity) {
backpack.merge(item, quantity, (oldQuantity, newQuantity) -> oldQuantity + newQuantity);
}
We insert the item and its quantity. If the item is not already present, it will be inserted with the passed quantity.
If it is already present, then the BiFunction which is a mapping function will be called with the existing value (oldQuantity) and the new value which we tried to insert (newQuantity). We sum them both, return it and the item's value (quantity) will be updated with this value.
Using method references, we can write the above as,
backpack.merge(item, quantity, Integer::sum);

How to correctly use polymorphism to call methods of the right class in Java

Suppose that I have a movie theater registration system.
And that I have a parent Customer class and a child MinorCustomer class.
MinorCustomer has a isAuthorized() method, which is not present in Customer, that returns true or false, meant to be called if the selected movie is not for unaccompanied minors
Now, when instantiating the classes to store the information in a data structure (whichever), I run into the issue that I cannot call isAuthorized() in the event that the client is a minor.
This is all hypothetical so there's no program with this code, but assuming the case would be
Customer cust = new Customer()
if(cust.getAge() < 18) {
cust = (MinorCustomer) cust;
cust.isAuthorized();
}
However, that code would not be valid, since it would still consider cust to be an instance of Customer, not MinorCustomer. I know that I could simply use an if statement to determine if I want to create a new instance of Customer/Minor depending on the age, but I'd like to take advantage of polymorphism to seamlessly change the type without having to write more rigid code.
Create a CustomerFactory that gives a customer of the appropriate type based on an age parameter instead.
Relying on the principle that
class Customer { }
class MinorCustomer extends Customer { }
...then an implementation of your factory could be:
class CustomerFactory {
public static Customer createInstance(final int age) {
if(age < 18) {
return new MinorCustomer();
} else {
return new Customer();
}
}
}
...which can then be used in your code like so.
Customer cust = CustomerFactory.createInstance(17);
You can enforce instanceof checks in methods that require that the Customer is not a MinorCustomer, or you can do an age check on the customer since you can get that information for free anyway.
You're missing a key concept here: that a customer is a customer. Whether it's minor, gold, major, silver, credible, bankrupt; it's a customer. This is part of basic OOP object identification, in my opinion.
Behind these sentences that state the obvious is a fundamental concept: you must have a definition of "customer" and whatever you call customer must meet it, although it may remain free to choose "how" they meet it.
Now, to make that practical: if you have a Customer class that is extended by MinorCustomer and other sub-classes, you need to declare the common behavior that's applicable to all customers in the Customer class. Polymorphism hinges on this. If a "customer" knows of nothing like "is authorized", then you can't introduce polymorphic "is authorized" behavior.
To use an example:
class Customer {
final int getAge() {
//return
}
boolean isAuthorized() {
return true;
}
}
class MinorCustomer extends Customer {
private boolean parentPresent;
#Override
boolean isAuthorized() {
return this.parentPresent;
}
}
In the above code, the "definition" of a "customer" includes the concept of "being authorized". A "minor customer", however, is free to choose "how" it meets that definition.
It's as simple as that, you need your Customer API to declare the isAuthorized() method, and have that overridden in MinorCustomer. This, of course, may be inadequate for your design; and that's fine: it would simply mean that the place is not right for polymorphic behavior (and perhaps also that the inheritance relationship should be questioned).
And you can extend this reasoning to other examples as well, the parent-to-child relationship must include the declaration of behavior in the parent for polymorphism to be applicable.
As for the mechanics of cleanly creating related objects, Makoto's post gives a good approach.
You need to add isAuthrorized property in Customer class.
and logic should like this
Customer cust = new Customer(...);
if(cust.getAge() > 18){
//skip authorization
cust.isAuthrorized = true;
}else{
authorize.user(cust);
//set isAuthrorized in authorization class based on user authentication fail or not
}
Sample in C#
abstract class Customer
{
public string Name { get; private set; }
public string Surname { get; private set; }
public string Id { get; private set; }
public Customer(string id, string name, string surname)
{
Id = id;
Name = name;
Surname = surname;
}
public abstract bool IsAuthorized();
}
class MajorCustomer : Customer
{
public MajorCustomer(string id, string name, string surname):base(id, name, surname)
{
}
public override bool IsAuthorized()
{
return true;
}
}
class MinorCustomer : Customer
{
public MinorCustomer(string id, string name, string surname) : base(id, name, surname)
{
}
public override bool IsAuthorized()
{
return false;
}
}
class Factory
{
public static Customer CreateCustomer(int age, string id, string name, string surname)
{
if (age < 18)
{
return new MinorCustomer(id, name, surname);
}
else
{
return new MajorCustomer(id, name, surname);
}
}
}
class Program
{
static void Main(string[] args)
{
Customer customer = Factory.CreateCustomer(21, "15612342", "Bob", "Snow");
if(customer.IsAuthorized())
{
Console.WriteLine("Customer is authorized");
}
else
{
Console.WriteLine("Customer is not authorized");
}
}
}

Is there a better way of accessing ArrayList object elements?

Took me a bit to figure this out but Im just wondering if there is a cleaner way to do this
this is the gist of my main
public class Main {
private static Bank Chase = new Bank();
//This is the function in main to add a transaction to a specified customer of a branch
public static void addTransaction() {
System.out.println("Enter the name of the branch");
String branch = scanner.nextLine();
System.out.println("Enter the name of the person");
String name = scanner.nextLine();
System.out.println("Enter the amount you would like to add");
double amount = scanner.nextDouble();
scanner.nextLine();
Chase.getBranchList().get(Chase.branchIndex(branch)).getCustomerList().get(Chase.getBranchList().get(Chase.branchIndex(branch)).customerIndex(name)).addTransaction(amount);
}
}
This last line is really long and confusing to others this is what it does
//gets the branchlist -> gets the specified branch -> gets the customerlist -> finds the specified customer -> adds transaction
these are the other relevant parts of the classes the function references
public class Bank {
private ArrayList<Branch> branchList = new ArrayList<Branch>();
public ArrayList<Branch> getBranchList() {
return branchList;
}
public int branchIndex(String name){
for(Branch branch: branchList){
if(branch.getName().equals(name)){
return branchList.indexOf(branch);
}
}
return -1;
}
}
public class Branch {
private String branchName;
private ArrayList<Customer> customerList;
public ArrayList<Customer> getCustomerList() {
return customerList;
}
public int customerIndex(String name){
for(Customer customer: customerList){
if(customer.getName().equals(name)){
return customerList.indexOf(customer);
}
}
return -1;
}
public class Customer {
private String customerName;
private ArrayList<Double> transactions = new ArrayList<Double>();
public Customer(String customerName, double amount) {
this.customerName = customerName;
this.transactions = new ArrayList<Double>();
transactions.add(amount);
}
public String getName() {
return customerName;
}
public void addTransaction(double transaction){
transactions.add(transaction);
}
}
So is there any more readable way of accessing these elements that are in object ArrayLists? I think the last line in addTransaction() looks a bit redundant.
Rather than one long line you could
a) split the code into multiple lines
Chase.getBranchList().get(Chase.branchIndex(branch))
.getCustomerList()
.get(Chase.getBranchList()
.get(Chase.branchIndex(branch))
.customerIndex(name))
.addTransaction(amount);
b) stored the returned values of each get into a local variable, especially the code that it re-calling the same methods e.g. Chase.branchIndex(branch) and Chase.getBranchList()
At the moment you are assuming unique customer/branch names, and then cycling through your array list to find the customer by name. This assumption is fine, if it's a valid assumption but could mean that there are more optimal solutions. I would recommend a refactor of your code to utilise a java hash map:
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Basically, this will mean that you can access the customer/bank directly by name and will simplify your code greatly! It will also have performance benefits.
For your scenario this refactor would look similar to this:
public class Branch
{
private HashMap<String, Customer> _customers;
private String _branchName;
public Branch(String branchName)
{
_branchName = branchName;
_customers = new HashMap<String, Customer>();
}
public Customer getCustomer(String customerName)
{
return _customers.get(customerName);
}
}
If you follow the same for Bank, you should be able to access a Customer and add a transaction as follows:
Chase.getBranch(branch).getCustomer(name).addTransaction(transaction);
Let me know if you need help converting Bank :)
You are on the right track, but you've got some minor design flaws.
Step 1: Add a method called getBranchByName(String branchName) to your Bank class that returns a Branch object and get rid of your branchIndex() method:
public Branch getBranchByName(String branchName) {
return branchList.stream()
.filter(branch -> branch.getBranchName().equals(branchName))
.findAny()
.get();
}
Step 2: Add a method called getCustomerByName(String name) to your Customer class that returns a Customer object and get rid of your customerIndex() method:
public Customer getCustomerByName(String name) {
return customerList.stream()
.filter(customer -> customer.getCustomerName().equals(name))
.findAny()
.get();
}
Step 3: Now, method call in your main() method becomes more compact, simple and easy to read:
Chase.getBranchByName(branchName).getCustomerByName(customerName).addTransaction(amount);
Note: I've used Java 8 streams as you can observe. If you are not allowed to use Java 8 streams, you can just stick with classic imperative style of programming by writing for() loops as you have done earlier. As a quick example, if you want to write getBranchByName(String branchName) in old fashioned Java 7 style, your loop looks like this:
for(Branch branch : branchList) {
if(branch.getBranchName().equals(branchName)){
return branch;
}
}

Adding subcategories to a java Enum

Suppose I have a simple Java Enum:
public Enum itemType
{
FRUITS("fru"),
VEGETABLES("veg"),
LIQUOURS("liq"),
SODAS("sod");
private String dbCode;
public ItemType(String dbCode){
this.dbCode = dbCode;
}
public String getDbCode(){
return this.dbCode;
}
}
I would now like to introduce a "category" to this enum, for example to make the distinction between liquid items and solid items. I found two ways of doing this within the enum class, see below. However, both suffer from the same anti-pattern: if the amount of categories or amount of items ever increases/decreases (imagine 100 item types with 10 categories!), I've got a lot of updating to do. What patterns can I use to design this enum as cleanly and re-usable as possible?
First approach: Add additional properties to the enum
public Enum itemType
{
FRUITS("fru",false),
VEGETABLES("veg",false),
LIQUOURS("liq",true),
SODAS("sod",true);
private String dbCode;
private boolean liquid;
public ItemType(String dbCode, boolean liquid){
this.dbCode = dbCode;
this.liquid = liquid;
}
public String getDbCode(){
return this.dbCode;
}
public boolean isLiquid(){
return this.liquid;
}
}
Second approach: Use static methods to ask about subcategories
public Enum itemType
{
FRUITS("fru"),
VEGETABLES("veg"),
LIQUOURS("liq"),
SODAS("sod");
private String dbCode;
public ItemType(String dbCode){
this.dbCode = dbCode;
}
public String getDbCode(){
return this.dbCode;
}
public static boolean isLiquid(ItemType type){
switch(t){
case SODA:
case LIQOURS: return true;
default: return false;
}
}
How about using an EnumSet for that?
public enum ItemType
{
FRUITS("fru"),
VEGETABLES("veg"),
LIQUOURS("liq"),
SODAS("sod");
public static final EnumSet<ItemType> LIQUIDS = EnumSet.of(LIQUOURS, SODAS);
// ...
}
Then you can use ItemType.LIQUIDS.contains(someItemType) to check if someItemType is a "liquid".
I would do something like:
enum Category {
LIQUID, SOLID;
}
enum ItemType {
FRUITS("fru", SOLID),
VEGETABLES("veg", SOLID),
LIQUOURS("liq", LIQUID),
SODAS("sod", LIQUID);
private String dbCode;
private Category category;
public ItemType(String dbCode, Category category){
this.dbCode = dbCode;
this.category = category;
}
/* getters / setters */
}
That would allow, for example, that you can add new products and categories (e.g. BUTANE("but", GAS)) without having to modify the existing code (as would happen in Approach 2).
On the other hand, if the number of categories and items is long and changing, I would consider to use a SQL database.
Since you are modeling something that has no logic that can be encoded in an algorithmic way (i.e. there's no algorithm that would figure out that "sod" is liquid and "veg" is not) there is no way around enumerating all related pairs of (item, category) in one way or the other.
There are three approaches to implementing it:
Enumerate categories on item's side - this is what your code does in both cases, or
Enumerate items on category's side - this would build an enum of categories, and attach a full list of items to each of them, or
Enumerate item+category pairs independently - this approach may be useful when storing item/category mapping in the database or in a configuration file.
I would recommend taking the third approach as it is the most "symmetric" one. Make a table for categories with category codes, and add a "cross-table" (or a cross-file) that has all pairs of categories and their corresponding items. Read the cross table/file at startup, and set up the dependencies on both sides.
public Enum ItemType {
FRUITS("fru")
, VEGETABLES("veg")
, LIQUOURS("liq")
, SODAS("sod");
public void addCategory(ItemCategory category) ...;
public EnumSet<ItemCategory> getItemCategories() ...;
}
public Enum ItemCategory {
LIQUIDS("liq")
, SNACKS("snk")
, FAST("fst");
public void addItem(ItemType type) ...;
public EnumSet<ItemType> getItemTypes() ...;
}
Cross-file or cross-table may look like this:
liq liq
sod liq
fru snk
fru fst
sod fst
You process it by enumerating pairs, and calling addCategory on the pair's item side, and calling addItem on the pair's category side.
These were three excellent answers, but I think I can combine all three in one nice package:
public enum ItemType {
FRUITS("fru",PERISHABLE),
VEGETABLES("veg",PERISHABLE),
LIQUOURS("liq",LIQUIDS),
SODAS("sod",LIQUIDS),
FRESH_SQUEEZED_ORANGE_JUICE("orgj",LIQUIDS,PERISHABLE);
private final String dbCode;
private final EnumSet<ItemCategory> categories;
private static final Map<ItemCategory,Set<ItemType>> INDEX_BY_CATEGORY = new EnumMap<>(ItemCategory.class);
ItemType(String dbcode,ItemCategory... categories) {
this.dbCode = dbcode;
this.categories = EnumSet.copyOf(Arrays.asList(categories));
//for (ItemCategory c:categories) {
// // Illegal Reference to Static Field!
// INDEX_BY_CATEGORY.put(c, this);
//}
}
static {
for (ItemCategory c:ItemCategory.values()) {
INDEX_BY_CATEGORY.put(c, EnumSet.noneOf(ItemType.class));
}
for (ItemType t:values()) {
for (ItemCategory c:t.categories) {
INDEX_BY_CATEGORY.get(c).add(t);
}
}
}
public boolean is(ItemCategory c) {
return INDEX_BY_CATEGORY.get(c).contains(this);
}
public Set<ItemType> getAll(ItemCategory c) {
return EnumSet.copyOf(INDEX_BY_CATEGORY.get(c));
}
public String getDbCode() {
return dbCode;
}
}
Now,
we can easily ask about additional subcategories without writing the code for it: boolean isVegetableLiquid = VEGETABLES.is(LIQUIDS);
we can easily assign not only one, but multiple categories to an item as you can see for FRESH_SQUEEZED_ORANGE_JUICE.
we are using EnumSet and EnumMap for performance, including their methods like contains.
we absolutely are minimizing the amount of code required to add an additional item. This could be further minimized by setting this up by database or configuration. However, in that case we would have to avoid the use of Enum as well.

Infinite loop when trying to populate a list of no more than two Hospitals

In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.

Categories

Resources