this is a snippet of a bigger project. The project is designed to be a customer manager of customers + a job manager of money transfers. Before I can continue, I have a "small" problem I do not understand. I wonder, why
System.out.println(myJobOrganizer.jobNumber); // in the Main.java
outputs 0, allthough I have added two jobs to the jobList. When printing the jobList itself, it prints out
[[[customer1;adress1;accountBalance1];[customer2;adress2;accountBalance2];moneyToTransfer];[[customer3;adress3;accountBalance3];[customer4;address4;accountBalance4];moneyToTransfer2]]
jobOrganizer.java
import java.util.ArrayList;
import java.util.List;
public class jobOrganizer {
private static final jobOrganizer myJobOrganizer = new jobOrganizer();
public static jobOrganizer getMyJobOrganizer() {
return myJobOrganizer;
}
private List<job> jobList = new ArrayList<job>();
public int jobNumber = jobList.size();
public void add_job(job newJob) {
this.jobList.add(newJob);
}
public Iterable<job> all_jobs() {
return this.jobList;
}
public static jobOrganizer getInstance() {
return myJobOrganizer;
}
}
job.java
public class job implements Runnable {
private customer kunde1;
private customer kunde2;
private Double transfer;
public job(customer kunde1, customer kunde2, Double transfer) {
this.kunde1 = kunde1;
this.kunde2 = kunde2;
this.transfer = transfer;
}
#Override
public String toString() {
return "[" + kunde1 + "; " + kunde2 + "; " + transfer + "]";
}
public void run() {
System.out.println("Starting transfer");
Double geber = this.kunde1.getAccountBalance();
Double nehmer = this.kunde2.getAccountBalance();
Double geberNeu = geber - this.transfer;
this.kunde1.setAccountBalance(geberNeu);
Double nehmerNeu = nehmer + this.transfer;
this.kunde2.setAccountBalance(nehmerNeu);
System.out.println("Transfer done");
}
}
Main.java
public class Main {
public static void main(String[] args) {
customerOrganizer myCustomerOrganizer = new customerOrganizer();
jobOrganizer myJobOrganizer = new jobOrganizer();
customer mueller = new customer("Tim Mueller", "Strasse 1", 1077.00);
customer john = new customer("John Doe", "Strasse 2", 503.00);
customer meier = new customer("John Meier", "Strasse 3", 8500.50);
customer wurst = new customer("Hans Wurst", "Strasse 4", 1000.00);
myCustomerOrganizer.add_customer(mueller);
myCustomerOrganizer.add_customer(john);
myCustomerOrganizer.add_customer(meier);
myCustomerOrganizer.add_customer(wurst);
job transfer1 = new job(meier, wurst, 500.50);
job transfer2 = new job(mueller, john, 77.00);
myJobOrganizer.add_job(transfer1);
myJobOrganizer.add_job(transfer2);
System.out.println(myJobOrganizer.jobNumber);
System.out.println(myJobOrganizer.all_jobs().toString());
}
}
public int jobNumber = jobList.size(); isn't getting updated so do it like this, this will return the current jobList and not store an instance of it like your field did.
public int jobNumber(){
return jobList.size();
}
it is because the below code executed while object creation but not after that and you are not updating the value later.
public int jobNumber = jobList.size();
Related
I have this class ( DoctorRegistrationTest.java ) and having the global variable doctorCode , doctorFirstName , doctorFamilyName )
#BeforeMethod(groups = {"BVT", "Regression"})
public void loadRmsPage() {
loadRmsProfile();
softAssert = new SoftAssert();
doctorRegistrationPage = new DoctorRegistrationPage(webDriver);
}
#Epic("RMS - Create Doctor")
#Feature("RMS - Create Doctor functionality")
#Story("AUT-688")
#Severity(SeverityLevel.BLOCKER)
#Test(description = "Positive : Doctor Creation ", groups = {"BVT", "Regression"})
public void createDoctorTestMethod() {
do {
doctorCode = String.valueOf(generateRandomNumber(1000, 9999));
} while (false && doctorRegistrationPage.verifyCreatedDoctor(doctorCode));
setDoctorRegistrationInformation();
createDoctor();
}
public void createDoctor() {
doctorRegistrationPage.loadDoctorRegistrationPage();
doctorRegistrationPage.fillDoctorNameInformation(doctorCode, doctorFirstName, doctorFamilyName, doctorFirstNameInArabic, doctorFamilyNameInArabic);
doctorRegistrationPage.fillDoctorGeneralInformation(dateOfBirth, joinDate, identityNo, expiryDate, gender, doctorTitle, employmentType, identityType);
doctorRegistrationPage.fillDoctorContactInformation(mobileNumber, companyEmail);
doctorRegistrationPage.fillDoctorOtherInformation(doctorInformationEnglish, doctorInformationArabic);
doctorRegistrationPage.fillDoctorTiming(followUpDays, slotDurationMinutes);
doctorRegistrationPage.fillDoctorHospitalsAndClinics(hospital, clinics);
doctorRegistrationPage.fillDoctorDefaultProcedure(defaultProcedur, consultationProcedure);
boolean result = doctorRegistrationPage.verifyCreatedDoctor(doctorCode);
LOG.info("Return value of verifyCreatedDoctor method " + result);
softAssert.assertTrue(result, "TEST FAILED - CREATED DOCTOR NOT LISTING IN THE GRID");
softAssert.assertAll();
doctorRegistrationPage.logOutUser();
}
public void setDoctorRegistrationInformation() {
readPropertiesFile();
setNames();
setNumberValues();
setDate();
}
public void setNames() {
doctorFirstName = "AUT DN " + getRandomStringName(4);
doctorFamilyName = "AUT DFN " + getRandomStringName(4);
companyEmail = getRandomStringName(5) + "#aut.com";
doctorInformationEnglish = getRandomStringName(6);
}
public String getRandomStringName(int randomStringLength) {
return RandomStringUtils.randomAlphabetic(randomStringLength).toLowerCase();
}
public int generateRandomNumber(int low, int high) {
return (new Random()).nextInt(high - low) + low;
}
}
I have another class ( DoctorScheduleTest.java ) and needs to pass doctorCode , doctorFirstName , doctorFamilyName from (DoctorRegistrationTest.java ) to doctorSchedulePage.selectDoctorDropdown(doctor); method, instead of hardcoding the detail. Must pass the value like this (" doctorCode: doctorFirstName doctorFamilyName )
private String doctor =" 8938: AUT DN gvgl AUT DFN wnrn ";
#BeforeMethod(groups = {"BVT", "Regression"})
public void loadRmsPage()
{
loadRmsProfile();
softAssert = new SoftAssert();
doctorSchedulePage = new DoctorSchedulePage(webDriver);
}
#Epic("RMS")
#Feature("RMS - Create Doctor Schedule functionality")
#Story("AUT-835")
#Severity(SeverityLevel.BLOCKER)
#Test(description = "Positive : Doctor Schedule Creation", groups = {"BVT", "Regression"})
public void doctorScheduleCreationTestMethod()
{
setTemplateName();
createInitialSchedule();
setSchedule();
saveTemplate();
setTemplate();
setDateRange();
generateSchedule();
}
public void createInitialSchedule()
{
doctorSchedulePage.loadDoctorScheduleDashboard();
doctorSchedulePage.selectHospitalDropDown(hospital);
doctorSchedulePage.selectClinicDropDown(clinic);
doctorSchedulePage.selectDoctorDropdown(doctor);
doctorSchedulePage.fillTemplate(scheduleTemplateName);
}
public void setSchedule()
{
doctorSchedulePage.sundaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.mondaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.tuesdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.wednesdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.thursdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.fridaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.saturdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
}
public void saveTemplate()
{
doctorSchedulePage.saveTemplate();
}
public void setTemplate()
{
doctorSchedulePage.selectTemplateDropdown(scheduleTemplateName);
}
public void setDateRange()
{
doctorSchedulePage.selectScheduleDate(scheduleStartDate,scheduleEndDate);
}
public void generateSchedule()
{
doctorSchedulePage.generateSchedule();
}
public int generateRandomNumber(int low, int high)
{
return (new Random()).nextInt(high - low) + low;
}
public void setTemplateName()
{
scheduleTemplateName = "Template " + getRandomStringName(3);
}
public String getRandomStringName(int randomStringLength)
{
return RandomStringUtils.randomAlphabetic(randomStringLength).toLowerCase();
}
}
DoctorSchedulePage.java ( selectDoctorDropdown method )
public void selectDoctorDropdown(String doctorcode)
{
selectValueFromDropDown(doctorDropdown, doctorcode);
}
BasePage.java (selectValueFromDropDown method )
protected void selectValueFromDropDown(WebElement element, String value) {
if (value != null && !value.isEmpty()) {
waitForElementToPresent(element);
Select dropdown = new Select(element);
LOG.info("Selected "+value);
dropdown.selectByVisibleText(value);
}
}
First of all, your question indicates, that you have an issue with passing a test data into tests. That should be addressed in the first place.
Since that is another topic (and a much bigger one) I would recommend a workaround, using a separate class, with a doctor's data.
public static class Doctor{
public static String FirstName;
public static String FamilyName;
Initialize the data in the setup and use is whenever you need.
As I said before, that is not the best solution, as testing data should be kept outside of the tests, but might be helpful for now.
i have a method that puts some value(obtained from an excel file) into a hashmap with an array as the key
public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws
IOException
{
System.out.println(engine.txtY + "Processing HashMap "
+ "sbsBusServiceData..." + engine.txtN);
int counterPass = 0, counterFail = 0, stopCounter = 0;
String dataExtract, x = "";
String[] stopInfo = new String[3];
List<String[]> stopsData = new ArrayList<String[]>();
List<String> serviceNum = new Vector<String>();
HashMap<List<String>, List<String[]>> sbsBusServiceData =
new HashMap<List<String>, List<String[]>>();
String dataPath = this.dynamicPathFinder(
"Data\\SBS_Bus_Routes.csv");
BufferedReader sbsBusServiceDataPop = new BufferedReader(
new FileReader(dataPath));
sbsBusServiceDataPop.readLine();
//Skips first line
while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
try {
String[] dataParts = dataExtract.split(",", 5);
if (!dataParts[4].equals("-")){
if (Double.parseDouble(dataParts[4]) == 0.0){
sbsBusServiceData.put(serviceNum, stopsData);
String serviceNum1 = "null", serviceNum2 = "null";
if(!serviceNum.isEmpty()){
serviceNum1 = serviceNum.get(0);
serviceNum2 = serviceNum.get(1);
}
System.out.println("Service Number " + serviceNum1
+ ":" + serviceNum2 + " with " + stopCounter
+ " stops added.");
stopCounter = 0;
//Finalizing previous service
serviceNum.Clear();
serviceNum.add(0, dataParts[0]);
serviceNum.add(1, dataParts[1]);
//Adding new service
}
}
stopInfo[0] = dataParts[2];
stopInfo[1] = dataParts[3];
stopInfo[2] = dataParts[4];
stopsData.add(stopInfo);
//Adding stop to service
stopCounter++;
counterPass++;
}
catch (Exception e) {
System.out.println(engine.txtR + "Unable to process "
+ dataExtract + " into HashMap sbsBusServiceData."
+ engine.txtN + e);
counterFail++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG + counterPass + " number of lines"
+ " processed into HashMap sbsBusServiceData.\n" + engine.txtR
+ counterFail + " number of lines failed to process into "
+ "HashMap sbsBusServiceData.");
return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction},
// <{RouteSequence, bsCode, Distance}>
this method work for putting the values into the hashmap but i cannot seem to get any value from the hashmap when i try to call it there is always a nullpointerexception
List<String> sbsTest = new Vector<String>();
sbsTest.add(0, "10");
sbsTest.add(1, "1");
System.out.println(sbsBusServiceData.get(sbsTest));
try{
List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
String x = sbsServiceResults.get(1)[0];
System.out.println(x);
} catch(Exception e){
System.out.println(txtR + "No data returned" + txtN + e);
}
this is a sample of the file im reading the data from:
SBS
How can i get the hashmap to return me the value i want?
Arrays are not suitable as keys in HashMaps, since arrays don't override Object's equals and hashCode methods (which means two different array instances containing the exact same elements will be considered as different keys by HashMap).
The alternatives are to use a List<String> instead of String[] as the key of the HashMap, or to use a TreeMap<String[]> with a custom Comparator<String[]> passed to the constructor.
If you are having fixed array size then the example I'm posting might be useful.
Here I've created two Object one is Food and Next is Product.
Here Food object is use and added method to get string array.
public class Product {
private String productName;
private String productCode;
public Product(String productName, String productCode) {
this.productName = productName;
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Food Model Class: Use as a Object instead of String[] and achieve String[] functionality.
public class Food implements Comparable<Food> {
private String type;
private String consumeApproach;
public Food(String type, String consumeApproach) {
this.type = type;
this.consumeApproach = consumeApproach;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConsumeApproach() {
return consumeApproach;
}
public void setConsumeApproach(String consumeApproach) {
this.consumeApproach = consumeApproach;
}
public String[] FoodArray() {
return new String[] { this.type, this.consumeApproach };
}
//Implement compareTo method as you want.
#Override
public int compareTo(Food o) {
return o.getType().compareTo(this.type);
}
}
Using HashMap example
public class HashMapKeyAsArray {
public static void main(String[] args) {
HashMap<Food,List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static HashMap<Food,List<Product>> dataSetLake(){
HashMap<Food,List<Product>> data = new HashMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple","123"));
fruitA.add(new Product("Banana","456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato","999"));
vegetableA.add(new Product("Tomato","987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple","123"));
fruitB.add(new Product("Banana","456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato","999"));
vegetableB.add(new Product("Tomato","987"));
Food foodA = new Food("Fruits","Read To Eat");
Food foodB = new Food("Vegetables","Need To Cook");
Food foodC = new Food("VegetablesC","Need To Cook C");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodC, vegetableA);
return data;
}
Using TreeMap example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class TreeMapKeyAsArray {
public static void main(String[] args) {
TreeMap<Food, List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static TreeMap<Food, List<Product>> dataSetLake() {
TreeMap<Food, List<Product>> data = new TreeMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple", "123"));
fruitA.add(new Product("Banana", "456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato", "999"));
vegetableA.add(new Product("Tomato", "987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple", "123"));
fruitB.add(new Product("Banana", "456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato", "999"));
vegetableB.add(new Product("Tomato", "987"));
Food foodA = new Food("Fruits", "Read To Eat");
Food foodB = new Food("Vegetables", "Need To Cook");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodB, vegetableA);
return data;
}
}
Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}
Hi everyone i've produced an agent based model. The agents can move randomly and use the A* algorithm to move to places to places. There are two main collections 1) arrival Queue (arraylist) and the 2) main agents (arraylist). All the agents are initially placed into the arrival queue, agents are placed into the simulation at certain time intervals e.g. 100 agents per 400 simulation steps).
The issue im getting is every time I increase the population of agents from 3000+ the simulation begins to lag. Also im using the Java 2D libraries for visualizing the 2D array of agents. Bellow ive added a screenshot of the the visualVM of my application is shows the methods which are being called the most (CPU time).
ScreenShot Here
Model code:
package Model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import Model.Grid;
import Agent.*;
public class Model extends AbstractModel implements Runnable{
private Grid grid;
private Constants modelConstants;
private RandomGenerator randGenerator;
private GridMapLayout Maplayout;
private RoomController roomController;
private AgentFactory agentFacory;
private Statistics stats;
private ArrayList<AbstractAgent> agents;
private Queue<Patient> patientArrivalQueue;
private List<Patient> dischargedPatients;
private Queue<Doctor> doctorsQueue;
private Queue<Nurse> nursesQueue;
private int patientPopulation;
private int doctorPopulation;
private int receptionNurses;
private int aNeNurses;
private int ward1Nurses;
private int ward2Nurses;
private int ward3Nurses;
private boolean running;
private int currentSimCycle;
private int simArrivalCounter;
public CTimer timer = new CTimer();
public Model() {
super();
this.grid = new Grid(150, 150); //if no given size grid uses default size
this.modelConstants = new Constants();
this.randGenerator = new RandomGenerator(modelConstants.getSEED());
this.Maplayout = new GridMapLayout(this);
this.roomController = new RoomController(this);
this.agentFacory = new AgentFactory(this);
this.stats = new Statistics(this);
this.currentSimCycle = 0;
this.simArrivalCounter = 0;
this.agents = new ArrayList<AbstractAgent>();
this.patientArrivalQueue = new LinkedList<Patient>();
this.dischargedPatients = new LinkedList<Patient>();
this.doctorsQueue = new LinkedList<Doctor>();
this.nursesQueue = new LinkedList<Nurse>();
loadModelConstants();
loadMapLayout();
roomController.readyRoomCollections();
createAllAgents();
loadDoctorsInRooms();
loadNursesInRooms();
loadNextPatientArrival();
// randomlyPopulateGrid();
stats.updateStatistics();
stats.setDataValid(false);
// Room entrance = roomController.getAllRooms().get("Entrance");
// Room reception = roomController.getAllRooms().get("Reception");
// Room aNe = roomController.getAllRooms().get("A&E");
// Room ward1 = roomController.getAllRooms().get("Ward 1");
// Room ward2 = roomController.getAllRooms().get("Ward 2");
// Room ward3 = roomController.getAllRooms().get("Ward 3");
// Room canteen = roomController.getAllRooms().get("Canteen");
// Room toilet = roomController.getAllRooms().get("Toilet");
//
// System.out.println(toilet);
// System.out.println(entrance.getDoorLocations().size());
// System.out.println("Reception: " + reception.getRoomLocations().size());
// System.out.println("A&E: " + aNe.getRoomLocations().size());
// System.out.println("Ward 1: " + ward1.getRoomLocations().size());
// System.out.println("Ward 2: " + ward2.getRoomLocations().size());
// System.out.println("Ward 3: " + ward3.getRoomLocations().size());
// System.out.println("Canteen: " + canteen.getRoomLocations().size());
// System.out.println("Toilet: " + toilet.getRoomLocations().size());
}
public void loadModelConstants() {
this.patientPopulation = modelConstants.getPatientPopulation();
this.doctorPopulation = modelConstants.getDoctorPopulation();
this.receptionNurses = modelConstants.getReceptionNursePopulation();
this.aNeNurses = modelConstants.getaNeNursePopulation();
this.ward1Nurses = modelConstants.getWard1NursePopulation();
this.ward2Nurses = modelConstants.getWard2NursePopulation();
this.ward3Nurses = modelConstants.getWard3NursePopulation();
// System.out.println(this.patientPopulation);
// System.out.println(this.doctorPopuation);
// System.out.println(this.nursePopulation);
System.out.println("Loaded Model Constants");
}
public void loadMapLayout() {
Maplayout.loadMapImage();
Maplayout.loadRGBfileAndRooms();
Maplayout.readPixels();
Maplayout.addMapLayout();
// layout.printCells();
System.out.println("Loaded Map Layout");
}
public void createAllAgents() {
ArrayList<Patient> tempPatient = new ArrayList<Patient>();
ArrayList<Doctor> tempDoctor = new ArrayList<Doctor>();
ArrayList<Nurse> tempNurse = new ArrayList<Nurse>();
int totalNurses = + (modelConstants.getReceptionNursePopulation()
+ modelConstants.getaNeNursePopulation()
+ modelConstants.getWard1NursePopulation()
+ modelConstants.getWard2NursePopulation()
+ modelConstants.getWard3NursePopulation()
);
int noOfAgentLeftToCreate = modelConstants.getPatientPopulation() + modelConstants.getDoctorPopulation()
+ totalNurses;
while(tempPatient.size() != this.patientPopulation) {
Patient newPatient = (Patient) this.agentFacory.createAgent("PATIENT", noOfAgentLeftToCreate);
tempPatient.add(newPatient);
noOfAgentLeftToCreate--;
}
while(tempDoctor.size() != this.doctorPopulation) {
Doctor newDoctor = (Doctor)this.agentFacory.createAgent("DOCTOR", noOfAgentLeftToCreate);
tempDoctor.add(newDoctor);
noOfAgentLeftToCreate--;
}
while(tempNurse.size() != totalNurses) {
Nurse newNurse = (Nurse)this.agentFacory.createAgent("NURSE", noOfAgentLeftToCreate);
tempNurse.add(newNurse);
noOfAgentLeftToCreate--;
}
this.patientArrivalQueue.addAll(tempPatient); //Add total patients to arrive queue
this.doctorsQueue.addAll(tempDoctor); //Add all doctors to the doctors agent collection
this.nursesQueue.addAll(tempNurse); //Add all nurses to the nurse agent collection
System.out.println("All agents created");
}
public void loadDoctorsInRooms() {
for(Map.Entry<String, Room> pair : roomController.getDoctorRooms().entrySet()) {
String key = pair.getKey();
Room value = pair.getValue();
if(value.isRoomEmpty()) {
Doctor newDoctor = doctorsQueue.remove();
Location randFreeRoomLoc = value.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(newDoctor, newDoctor.getLocation(), randFreeRoomLoc);
newDoctor.setLocation(randFreeRoomLoc);
newDoctor.setAllocatedRoom(value);
newDoctor.getAgentController().setCurrentRoom(value);
newDoctor.getAgentController().setTargetRoom(value);
//Tell the room that this agent is now a occupant of the room
value.getCurrentOccupantsMap().put(newDoctor.getAgentID(), newDoctor);
agents.add(newDoctor);
}
}
Room aNeRoom = roomController.getAllRooms().get("A&E");
if(aNeRoom.isRoomEmpty()) {
Doctor aNeDoc = doctorsQueue.remove();
Location randFreeRoomLoc = aNeRoom.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(aNeDoc, aNeDoc.getLocation(), randFreeRoomLoc);
aNeDoc.setLocation(randFreeRoomLoc);
aNeDoc.setAllocatedRoom(aNeRoom);
aNeDoc.getAgentController().setCurrentRoom(aNeRoom);
aNeDoc.getAgentController().setTargetRoom(aNeRoom);
//Tell the room that this agent is now a occupant of the room
aNeRoom.getCurrentOccupantsMap().put(aNeDoc.getAgentID(), aNeDoc);
agents.add(aNeDoc);
}
System.out.println("All Doctors are placed");
}
public void loadNursesInRooms() {
HashMap<String, Room> nurseRooms = new HashMap<String, Room>();
nurseRooms.putAll( roomController.getAllRooms());
nurseRooms.remove("Toilet");
nurseRooms.remove("Canteen");
nurseRooms.remove("Staff");
nurseRooms.remove("Corridor");
nurseRooms.remove("ISOL Entrance");
nurseRooms.remove("Entrance");
nurseRooms.remove("Exit");
for(Map.Entry<String, Room> drPair : roomController.getDoctorRooms().entrySet()) {
String drKey = drPair.getKey();
Room drValue = drPair.getValue();
for(Map.Entry<String, Room> isolPair : roomController.getIsolRooms().entrySet()) {
String isolKey = isolPair.getKey();
Room isolValue = isolPair.getValue();
if(nurseRooms.containsKey(drKey)) {
nurseRooms.remove(drKey);
}
if(nurseRooms.containsKey(isolKey)) {
nurseRooms.remove(isolKey);
}
}
}
for(Map.Entry<String, Room> pair : nurseRooms.entrySet()) {
String key = pair.getKey();
Room value = pair.getValue();
int noOfNurseToCreate = 0;
if(key.contentEquals("Reception")) {
noOfNurseToCreate = modelConstants.getReceptionNursePopulation();
}
else if(key.contentEquals("A&E")) {
noOfNurseToCreate = modelConstants.getaNeNursePopulation();
}
else if(key.contentEquals("Ward 1")) {
noOfNurseToCreate = modelConstants.getWard1NursePopulation();
}
else if(key.contentEquals("Ward 2")) {
noOfNurseToCreate = modelConstants.getWard2NursePopulation();
}
else if(key.contentEquals("Ward 3")) {
noOfNurseToCreate = modelConstants.getWard3NursePopulation();
}
for(int i=0; i != noOfNurseToCreate; i++) {
Nurse newNurse = nursesQueue.remove();
Location roomLocation = value.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(newNurse, newNurse.getLocation(), roomLocation);
newNurse.setLocation(roomLocation);
newNurse.setAllocatedRoom(value);
newNurse.getAgentController().setCurrentRoom(value);
newNurse.getAgentController().setTargetRoom(value);
//Tell the room controller that this agent is now an occupant of the room
value.getCurrentOccupantsMap().put(newNurse.getAgentID(), newNurse);
agents.add(newNurse);
}
}
System.out.println("All Nurses are placed");
}
public void loadNextPatientArrival() {
if(this.simArrivalCounter == 0) {
int removeThemPatients = 0;
//If there are more patients in the arrival queue then the specified simPatientarrival rate then
//remove the specified amount of patients per simPatient arrival rate
if(patientArrivalQueue.size() >= modelConstants.getPatientArrivalRate()) {
removeThemPatients = modelConstants.getPatientArrivalRate();
}
//Number of patient to place on the grid is less then the patient arrival rate, just place the rest into the entrance
else {
removeThemPatients = patientArrivalQueue.size();
}
Room reception = roomController.getAllRooms().get("Reception");
Room aNe = roomController.getAllRooms().get("A&E");
for(int i=removeThemPatients; i !=0; i--) {
Patient nextPatient = patientArrivalQueue.remove();
// if(nextPatient.getPatientType().contains("Normal") & nextPatient.getLocation() != null) {
if(grid.checkEmptyAt(nextPatient.getLocation())) {
grid.placeAgent(nextPatient, nextPatient.getLocation());
agents.add(nextPatient);
}
else {
patientArrivalQueue.add(nextPatient);
}
// }
}
//IMPORTANT need to reset the simArrivalCounter back to the specified count
this.simArrivalCounter = this.modelConstants.getSimArrivalCounter();
// System.out.println("More patients have arrived");
}
}
public void removeDischargedPatients() {
//Just iterate through the exit room door locations and remove
//the the discharged patients waiting there into the patient discharge list
Room exit = roomController.getAllRooms().get("Exit");
for(Location loc : exit.getDoorLocations()) {
if(!grid.checkEmptyAt(loc)) {
Patient dischargedPatient = (Patient) grid.getAgentAtLocation(loc);
grid.clearLocationAt(loc);
agents.remove(dischargedPatient);
dischargedPatients.add(dischargedPatient);
}
}
}
public void randomlyPopulateGrid() {
Room reception = roomController.getAllRooms().get("Reception");
while(!this.patientArrivalQueue.isEmpty()) {
Location freeLoc = reception.getRandomFreeRoomLocation();
Patient nextPatient = this.patientArrivalQueue.remove();
grid.moveAgentToNewLocation(nextPatient, nextPatient.getLocation(), freeLoc);
nextPatient.setLocation(freeLoc);
nextPatient.getAgentController().setCurrentRoom(reception);
nextPatient.getAgentController().setTargetRoom(reception);
agents.add(nextPatient);
}
System.out.println("Populate Grid");
}
public void simulateCycles(int maxCycles) {
for(int i=0; i != maxCycles; i++) {
loadNextPatientArrival();
removeDischargedPatients();
updateAgents();
stats.updateStatistics();
stats.setDataValid(false);
this.currentSimCycle++;
this.simArrivalCounter--;
}
notifyViews();
}
public void updateAgents() {
// Iterator<AbstractAgent> it = agents.iterator();
// while(it.hasNext()) {
// AbstractAgent nextAgent = it.next();
// nextAgent.act();
// }
for(AbstractAgent agent : agents) {
agent.act();
}
}
#Override
public void startSimulation() {
new Thread(this).start();
System.out.println("Running Simulation");
}
#Override
public void stopSimulation() {
running = false;
System.out.println("Simulation has stoped");
}
#Override
public void resetSimulation() {
System.out.println("Model Constant set to default");
}
public void run() {
running = true;
// int loop = 0;
while(running) {
// System.out.println("loop: "+ loop);
// loop++;
simulateCycles(1);
try {
Thread.sleep(5);
}
catch (Exception e) {
}
}
}
public Grid getGrid() {
return grid;
}
public List<AbstractAgent> getAgentsCollection() {
return agents;
}
public GridMapLayout getGridMayLayout() {
return Maplayout;
}
public RoomController getRoomController() {
return roomController;
}
public Constants getModelConstants() {
return modelConstants;
}
public RandomGenerator getRandGenerator() {
return randGenerator;
}
public int getCurrentSimCycle() {
return currentSimCycle;
}
public Statistics getStats() {
return stats;
}
}
This is a characteristic of time-stepped agent-based modeling. Since each of n agents can in principle interact with any of the other agents, there are n choose 2 interactions to be evaluated at each time step, which grows as O(n2). Your basic choices are: 1) keep the number of agents small; 2) increase the size of your time steps (which usually introduces modeling errors due to the coarser approximation of what's happening); 3) "localize" the scope of interactions (which may or may not be realistic for what you're modeling); or 4) rewrite your model to use discrete event scheduling rather than time stepping.
I am trying use a from a multi-dimensional array that I create in another classes method. Below is my main method:
public class main {
public static void main(String[] args) throws Exception {
sql test = new sql();
String[][] test2 = test.getDb();
System.out.print(test2[0][0]);
}
Now here is the class that returns an multi-dimensional array.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.mysql.jdbc.Statement;
public class sql {
java.sql.Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:8889/deliveryEarn";
String user = "root";
String password = "root";
ArrayList<String> sqlCol1 = new ArrayList<String>();
ArrayList<String> sqlCol2 = new ArrayList<String>();
ArrayList<String> sqlCol3 = new ArrayList<String>();
ArrayList<String> sqlCol4 = new ArrayList<String>();
ArrayList<String> sqlCol5 = new ArrayList<String>();
ArrayList<String> sqlCol6 = new ArrayList<String>();
ArrayList<String> sqlCol7 = new ArrayList<String>();
String sqlArray[][] = new String[7][7];
public sql() {
}
public String[][] getDb() {
try {
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("select * from incomeCalc");
rs = pst.executeQuery();
while (rs.next()) {
sqlCol1.add(rs.getString(1));
int i1=0;
for(String s: sqlCol1){
sqlArray[i1++][0] = s;
}
sqlCol2.add(rs.getString(2));
int i2=0;
for(String s: sqlCol2){
sqlArray[i2++][1] = s;
}
sqlCol3.add(rs.getString(3));
int i3=0;
for(String s: sqlCol3){
sqlArray[i3++][2] = s;
}
sqlCol4.add(rs.getString(4));
int i4=0;
for(String s: sqlCol4){
sqlArray[i4++][3] = s;
}
sqlCol5.add(rs.getString(5));
int i5=0;
for(String s: sqlCol5){
sqlArray[i5++][4] = s;
}
sqlCol6.add(rs.getString(6));
int i6=0;
for(String s: sqlCol6){
sqlArray[i6++][5] = s;
}
sqlCol7.add(rs.getString(7));
int i7=0;
for(String s: sqlCol7){
sqlArray[i7++][6] = s;
}
}
}
catch( Exception E ) {
System.out.println( E.getMessage() );
}
return sqlArray;
}
}
Here is the screenshot of the MySQL database.
Edit: It appears I wasn't clear with my question. I apologize. I am getting a runtime error at this line:
System.out.print(test2[0][0]);
What am I doing wrong? Also, for correct OOP, is it better to use a constructor or a method to pull from or input to a database? THis is my first program so sorry if it seems trivial.
Edit2: Here is the error:
Exception in thread "main" java.lang.NullPointerException
at main.main(main.java:17)
As to why you've got an error, it would be nicer to know the error, however...
Personally, I'd drop the contents of the result set into a "Data Object"...
public class Income {
// Column decelerations...
private long id;
private int tips;
private int hours;
private int gas;
private double hourly;
private double other;
private double other2;
public int getGas() {
return gas;
}
public double getHourly() {
return hourly;
}
public int getHours() {
return hours;
}
public long getId() {
return id;
}
public double getOther() {
return other;
}
public double getOther2() {
return other2;
}
public int getTips() {
return tips;
}
public void setGas(int gas) {
this.gas = gas;
}
public void setHourly(double hourly) {
this.hourly = hourly;
}
public void setHours(int hours) {
this.hours = hours;
}
public void setId(long id) {
this.id = id;
}
public void setOther(double other) {
this.other = other;
}
public void setOther2(double other2) {
this.other2 = other2;
}
public void setTips(int tips) {
this.tips = tips;
}
}
Then when you load it you could do something like...
public Income[] getIncome() {
// Call database...
List<Income> data = new ArrayList<Income>(25);
while (rs.next()) {
Income income = new Income();
income.setID(rs.getInt(1)));
income.setTips(rs.getInt(2)));
income.setHours(rs.getInt(3)));
income.setGas(rs.getInt(4)));
income.setHourly(rs.getDouble(5)));
income.setOther(rs.getDouble(6)));
income.setOther2(rs.getDouble(7)));
data.add(income);
}
return data.toArray(new Income[data.size()]);
}
The you could do things like this...
sql test = new sql();
Income[] incomes = test.getIncome();
System.out.println(incomes[0].getID());
Isn't that easier to read :P
Your attempt to use a Factory is probably the best idea. It comes down to a matter of management as to weather you maintain a single instance (Singlton) or allow multiple instances of this Factory to be created. Personally, I prefer to use Singltons in this case where I can, it allows a centralised place to perform operations (saving changes, creating new objects, listing, deleting) and helps manage the resources involved. IMHO