How can I make the following parkinglot simulation asynchronous use RabbitMQ? - java

I'm trying to learn and undertand the different approaches to concurrency in java. I have with me a serialised implementation of a parking lot simulation. I want to make it so that the program uses Rabbitmq instead, how would I go about doing that?
Below is my parking-lot class, which, implementation wise could also be improved.
EDIT: I've realised that my main question is actually, how can I do the Pub/sub in a loop.2. Is pub/sub even necessary?
public class Parking {
public static void main(String[] args) throws InterruptedException {
Parking parkingObj = new Parking();
parkingObj.runSimulation();
}
public void runSimulation() throws InterruptedException{
int numOfRuns = 101;//100 runs
int currentRuns = 1;
securityGuard myGuard = new securityGuard();
//spot mySpot = new spot();
ArrayList<ticketClass> ticketArray = new ArrayList<>();
int bouncedCustomers = 1;
spot availableSpot = new spot();
//Random randomExit = new Random();
while (currentRuns < numOfRuns){
Random randomSleep = new Random();
//Car object instantiation
carClass vehicle = new carClass();
//ticketClass ticketObj = new ticketClass();
//Random time generator
Random randomTime = new Random();
//instantiation of the info geneatator class
infoGenerator info = new infoGenerator();
//Generaring random Car info
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
if (availableSpot.getSpotNum() == 15 ){
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Customers waiting for free space
Thread.sleep(9000);
System.out.println("Total Waiting customers: " + bouncedCustomers);
bouncedCustomers += 1;
}
else{
//System.out.println("Customer Exiting");
Thread.sleep(randomTime.nextInt(5000));
meterClass myMeter = new meterClass();
ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//ticketClass myTicket = new ticketClass();
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getCar().minSetter(randomTime.nextInt(100));
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
myMeter.setPurchasedMinutes(randomTime.nextInt(72));
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//myTicket.
ticketArray.add(myTicket);
System.out.println("\n\n===Total customers: " + ticketArray.size());
System.out.println(timeIn+"\n");
availableSpot.spotLog();
}
//Cars leaving at random times
for (int i= 0; i < ticketArray.size();i++ ){
meterClass meterOut = ticketArray.get(i).getMeter();
carClass ExitCar = ticketArray.get(i).getCar();
if(myGuard.checkParking(ExitCar,meterOut)){
System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
double penaltyVal = ticketArray.get(i).getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
Thread.sleep(randomTime.nextInt(4000));
ticketArray.remove(ticketArray.remove(i));
availableSpot.spotFree(i);
}
}
currentRuns += 1;
}
}
}
TLDR: I need to optimise the following code, both structure-wise and in terms of speed (Specifically using multithreading with RabbitMQ)
As it currently is, it runs in an infinite loop, and the fine value is 0. The security guard class which is responsible for this calculation is as such;
public class securityGuard{
public String badgeNumber;
public String guardName;
securityGuard(){}
securityGuard(String badgeNumber, String guardName){
this.badgeNumber = badgeNumber;
this.guardName = guardName;
}
public void setBadgeNumber(String badgeNumber){
this.badgeNumber = badgeNumber;
}
public String getBadgeNumber(){
return badgeNumber;
}
public void setguardName(String guardName){
this.guardName = guardName;
}
public String getGuardName(){
return guardName;
}
public boolean checkParking(carClass car,meterClass meter){
return car.minGetter() > meter.getPurchasedMinutes();
}
public ticketClass ticketGenerator(carClass car, meterClass meterVar){
ticketClass myTicket = new ticketClass(car,this);
int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();
if(checkParking(car,meterVar)){
if (timeRemaining < 60){
myTicket.penalty = 50;
}
else {
myTicket.penalty = 50 + (10 * (timeRemaining/60));
}
}
return myTicket;
}
}
Please let me know if you require any additional information regarding the other classes or if I left anything out .Thank you in advance
EDIT:
Below is my attempt at a producer implementation. I tried using a for loop in the run method with the goal of publishing 100 random messages
public class entrySimulation implements Runnable {
int numOfRuns = 100;//1000 runs
int currentRuns = 1;
securityGuard_exp_1 myGuard = new securityGuard_exp_1();
//System.out.println("Customer Exiting");
//Thread.sleep(randomTime.nextInt(5000));
meterClass_exp_1 myMeter = new meterClass_exp_1();
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
//instantiation of the info generator class
infoGenerator_exp_1 info = new infoGenerator_exp_1();
//Generating random Car info
//spot_exp_1 mySpot = new spot_exp_1();
//Use an iterator
List<ticketClass_exp_1> ticketArray = new ArrayList<>();
Iterator<ticketClass_exp_1> iter = ticketArray.iterator();
public final spot_exp_1 availableSpot = new spot_exp_1();
//Random time generator
Random randomTime = new Random();
public static void main(String[] args) {
String exchangeName = "entryExchange";
String routingKey = "exitKey";
String message = "";
//Creating a connection factory
ConnectionFactory factory = new ConnectionFactory();
//Creating new connection
try(Connection conVar = factory.newConnection();){
Channel channelCon = conVar.createChannel();
//Exchange declaration
channelCon.exchangeDeclare(exchangeName,"customerExit");
channelCon.basicPublish(exchangeName,routingKey,null,message.getBytes(StandardCharsets.UTF_8));
System.out.println("Customer Exited");
}catch(Exception e){}
}
#Override
public void run() {
for (int i = 0; i < numOfRuns; i++) {
//System.out.println(i);
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
myMeter.setPurchasedMinutes(randomTime.nextInt(30));
carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880));
ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//Generating details
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getGuard().setguardName("Phill");
myTicket.getGuard().setBadgeNumber("AF170");
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//message
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
System.out.println("Penalty" + myTicket.getPenalty());
ticketArray.add(myTicket);
System.out.println("============================================|");
System.out.println("TIME IN: " + timeIn);
//System.out.println("\n\n===Total customers: " + myTicket.slotNum);
//message
availableSpot.spotLog();
}
}
}
However, I'm not sure how to. Please if anyone can help in any way. Sorry, this is a very new concept to me

Related

How would I implement this Serialised parking lot simulation using to Executor services

I'm trying to understand the benefits of multithreading much better. I have with me a serialised implementation of a parking lot simulation. I want to make it so that the program uses Executor services instead, how would I go about doing that?
Below is my parking-lot class, the implementation could definitely be refined, I just can't seem to figure out how to.
public class Parking {
public static void main(String[] args) throws InterruptedException {
Parking parkingObj = new Parking();
parkingObj.runSimulation();
}
public void runSimulation() throws InterruptedException{
int numOfRuns = 101;//100 runs
int currentRuns = 1;
securityGuard myGuard = new securityGuard();
//spot mySpot = new spot();
ArrayList<ticketClass> ticketArray = new ArrayList<>();
int bouncedCustomers = 1;
spot availableSpot = new spot();
//Random randomExit = new Random();
while (currentRuns < numOfRuns){
Random randomSleep = new Random();
//Car object instantiation
carClass vehicle = new carClass();
//ticketClass ticketObj = new ticketClass();
//Random time generator
Random randomTime = new Random();
//instantiation of the info geneatator class
infoGenerator info = new infoGenerator();
//Generaring random Car info
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
if (availableSpot.getSpotNum() == 15 ){
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Customers waiting for free space
Thread.sleep(9000);
System.out.println("Total Waiting customers: " + bouncedCustomers);
bouncedCustomers += 1;
}
else{
//System.out.println("Customer Exiting");
Thread.sleep(randomTime.nextInt(5000));
meterClass myMeter = new meterClass();
ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//ticketClass myTicket = new ticketClass();
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getCar().minSetter(randomTime.nextInt(100));
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
myMeter.setPurchasedMinutes(randomTime.nextInt(72));
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//myTicket.
ticketArray.add(myTicket);
System.out.println("\n\n===Total customers: " + ticketArray.size());
System.out.println(timeIn+"\n");
availableSpot.spotLog();
}
//Cars leaving at random times
for (int i= 0; i < ticketArray.size();i++ ){
meterClass meterOut = ticketArray.get(i).getMeter();
carClass ExitCar = ticketArray.get(i).getCar();
if(myGuard.checkParking(ExitCar,meterOut)){
System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
double penaltyVal = ticketArray.get(i).getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
Thread.sleep(randomTime.nextInt(4000));
ticketArray.remove(ticketArray.remove(i));
availableSpot.spotFree(i);
}
}
currentRuns += 1;
}
}
}
TLDR: I need to optimise the following code, both structure-wise and in terms of speed (Specifically using multithreading with Executor service)
As it currently is, it runs in an infinite loop, and the fine value is 0. The security guard class which is responsible for this calculation is as such;
public class securityGuard{
public String badgeNumber;
public String guardName;
securityGuard(){}
securityGuard(String badgeNumber, String guardName){
this.badgeNumber = badgeNumber;
this.guardName = guardName;
}
public void setBadgeNumber(String badgeNumber){
this.badgeNumber = badgeNumber;
}
public String getBadgeNumber(){
return badgeNumber;
}
public void setguardName(String guardName){
this.guardName = guardName;
}
public String getGuardName(){
return guardName;
}
public boolean checkParking(carClass car,meterClass meter){
return car.minGetter() > meter.getPurchasedMinutes();
}
public ticketClass ticketGenerator(carClass car, meterClass meterVar){
ticketClass myTicket = new ticketClass(car,this);
int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();
if(checkParking(car,meterVar)){
if (timeRemaining < 60){
myTicket.penalty = 50;
}
else {
myTicket.penalty = 50 + (10 * (timeRemaining/60));
}
}
return myTicket;
}
}
Please let me know if you require any additional information regarding the other classes or if I left anything out .Thank you in advance

Simulating a Waiting line

I've been tasked as an assignment to make a queue, that is supposed to be simulated 10 times, and for it to have a waiting room that can hold 100 customers.
I was able to simulate it 10 times, but the assignment mentions criteria such as having an average waiting time of x minutes, having a minimum number of served customers, and at the end have a maximum number of those waiting in line.
Here are my classes
Customer.class
public class Customer {
int arrivalTime;
int transactionTime;
int customerNumber;
public Customer(int a, int t, int c) {
arrivalTime = a;
transactionTime = t;
customerNumber = c;
}
public int getArrivalTime() {
return arrivalTime;
}
public int getTransactionTime() {
return transactionTime;
}
public int getCustomerNumber() {
return customerNumber;
}
}
WaitLine.class
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class WaitLine {
private static QueueInterface<Customer> line;
private static int numberOfArrivals;
private static int numberServed;
private static int totalTimeWaited;
public WaitLine() {
line = new LinkedQueue<Customer>();
reset();
}
public final void reset() {
line.clear();
numberOfArrivals = 0;
numberServed = 0;
totalTimeWaited = 0;
}
public void simulate(int duration, double arrivalProbability, int maxTransactionTime) {
int transactionTimeLeft = 0;
for (int clock = 0; clock < duration; clock++) {
if (Math.random() < arrivalProbability) {
numberOfArrivals++;
int transactionTime = (int) (Math.random() * maxTransactionTime + 1);
Customer nextArrival = new Customer(clock, transactionTime, numberOfArrivals);
line.enqueue(nextArrival);
System.out.println("Customer " + numberOfArrivals + " enters line at time " + clock
+ ". Transaction time is " + transactionTime);
}
if(transactionTimeLeft > 0) {
transactionTimeLeft--;
}else if(!line.isEmpty()) {
Customer nextCustomer = line.dequeue();
transactionTimeLeft = nextCustomer.getTransactionTime()-1;
int timeWaited = clock - nextCustomer.getArrivalTime();
totalTimeWaited += timeWaited;
numberServed++;
System.out.println("Customer " + nextCustomer.getCustomerNumber() + " begins service at time " + clock + ". Time waited is " + timeWaited );
}
}
}
public void displayResults() {
System.out.println();
System.out.println("Number served = " + numberServed);
System.out.println("Total time Waited = " + totalTimeWaited);
double averageTimeWaited = ((double)totalTimeWaited) / numberServed;
System.out.println("Average time waited = " + averageTimeWaited);
int leftInLine = numberOfArrivals - numberServed;
System.out.println("Number left in line " + leftInLine);
}
}```
I am currently stuck on meeting the criteria described, I put the simulate function in a loop that looped 10 times and after that I used displayresults, but my results did not fit the criteria.
Any help is appreciated, thank you.
transactionTime is handled in the main method/simulation(s) and not on the customer instance itself. Yo just need the arrivalTime and departureTime, and the constructor only needs to be Customer( int arrives ). Then you just need getArrivalTime() setDepartureTime(int time) and totalTime()
Then use import java.util.*; with Queue<Customer> line = new LinkedList<Customer>() and from there you just need the main method using that queue and the customer class that I modified above.

Sorting array list

public class Saleitem {
public Product product = null;
public int numberofproduct = 0;
static ArrayList<Saleitem> Saleitemarray = new ArrayList<Saleitem>();
static ArrayList<Integer[]> total = new ArrayList<Integer[]>();
//read the sales data
public static void salesData() {
String SalesDataCSV = "SalesData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
System.out.println("\nThe Sales Data file has been opened\n");
try {
int currentcustomer = 1;
int lastcustomer = 1;
double sum = 0;
br = new BufferedReader(new FileReader(SalesDataCSV));
line = br.readLine();
System.out.println("-----------------------------------------------");
System.out.println("Sales Data File");
System.out.println("Customer ID, Product ID, Number of Units");
System.out.println("-----------------------------------------------");
while ((line = br.readLine()) != null) {
String field[] = line.split(cvsSplitBy);
if(field.length>1) {
String currentcustomerID = field[0];
String currentproductID = field[1];
String currentunitnumber = field[2];
Product currentproduct = null;
currentcustomer = Integer.parseInt(currentcustomerID);
int currentproductid = Integer.parseInt(currentproductID);
int currentproductunit = Integer.parseInt(currentunitnumber);
//-------------------------------------
// START OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
System.out.println(currentcustomer + " , " + currentproductid + " , " + currentproductunit);
////////////////////
if (lastcustomer == currentcustomer) {
Saleitem salesItemObject = new Saleitem(currentproductid, currentproductunit,
Product.getUnitPrice(currentproductid));
Saleitemarray.add(salesItemObject);
} else {
// sale receipt date, time, etc.
Salereceipt salesReceiptObject = new Salereceipt(lastcustomer, lastcustomer,
sum, "2/20/16", (int) (Math.random() * 2000));
Salereceipt.receipt.add(salesReceiptObject);
lastcustomer = currentcustomer;
Saleitemarray.clear();
sum = 0;
}
///////////////////////////
//Find the correct product that the customer ordered
for (int i = 0; i < Product.productData.size(); i++){
if (((Product.productData).get(i)).productID == currentproductid){
currentproduct = Product.productData.get(i);
}
}
Saleitem salesItemObject = new Saleitem(currentproduct, currentproductunit);
Saleitemarray.add(salesItemObject);
boolean found = false;
//update total
for (int i = 0; i < total.size(); i++){
//total is an array of arrays =)
//in the array, index 0 is the productID
// index 1 is the total sold of that product
//Find the correct product total
if ((total.get(i))[0] == salesItemObject.product.productID){
//if we found it then we will mark found
//so that we can add in the item if it doesnt exist
//in our total array
found = true;
//increment the total number of prodcuts sold
(total.get(i))[1] += salesItemObject.numberofproduct;
}
}
if (found == false){
Integer[] array = new Integer[2];
// index 0 = product id
// index 1 = total number of products sold
array[0] = salesItemObject.product.productID;
array[1] = salesItemObject.numberofproduct;
total.add(array);
}
//-------------------------------------
// END OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
//this is done inside of the constructor
if (currentcustomer == lastcustomer){
sum += currentproduct.productPrice * currentproductunit;
}
}
}
The Sales Data is imported from a file that has Customer_ID[0], Product_ID[1], Units_ordered[2]
I want to sort the ArrayList total by the Product_ID in ascending order. What would be the best way to do this. Im new to java so I don't know much of the syntax.
total.sort((item1, item2) -> item1.getProductId() - item2.getProductId());
You can use Collections#sort like below.
Add a getter for ProductId and you're done
Collections.sort(total, new Comparator<Saleitem>(){
#Override
public int compare(Saleitem s1, Saleitem s2) {
return s1.getProductId() - s2.getProductId();
}
});

Issue with Threading

I want to be able to use threads to run two loops at once within my program for a sort of game like program. However I'm not entirely sure how to use Threads and I am encountering errors I know nothing about. I will post code but ignore most of it, it's a somewhat hollow shell of what I want it to be I just need to get threads working to start cleaning it all up.
I'm getting the error "is not abstract and does not override" and it is highlighting the "class game implements runnable" section. This is the code:
public class game implements Runnable
{
#Override
public void run(int time){
try{
time = 1;
while (time<=10){
Thread.sleep(10);
System.out.print(time);
time++;
}
char clearer = (char)(12);
System.out.print(clearer);
System.out.println("You have ran out of time! Game over!");
System.exit(0);
}catch (Exception e){}
}
public static void main (String args[]) throws Exception{
System.out.println("Welcome to pseudo-Where's Wally, look for the lower cal l character.");
Thread.sleep(500);
System.out.println("You get 10 seconds to find it.");
Thread.sleep(500);
System.out.println("Ready?..");
char clear = (char)(12);
Thread.sleep(500);
System.out.print(clear);
boolean timer = false, col = false, guess = false;
int length = 5, time = 0, rowNum = 1, y = 0;
String manip = ("");
int x = (length*length);
Random gen = new Random();
int find = gen.nextInt(x)+1;
for (int collumn = 0; collumn<=length; collumn++){
for (int row = 0; row<=length; row++){
while (!col){
y++;
System.out.print(" "+y);
if (y-1 == length){
System.out.println();
System.out.println();
col = true;
}
}
System.out.print(" I");
manip = manip + (" I");
}
System.out.println("\t" + rowNum);
rowNum++;
manip = manip + (" I");
}
boolean contin = false;
do{
if (find%3==0){
contin = true;
find = find - 1;
} else if (find%3>0){
find = find - 1;
}
}while (!contin);
String newManip = manip.substring(0,find)+'l'+manip.substring(find+1);
String subOne = newManip.substring(0,18);
String subTwo = newManip.substring(18,36);
String subThree = newManip.substring(36,54);
String subFour = newManip.substring(54,72);
String subFive = newManip.substring(72,90);
String subSix = newManip.substring(90,108);
System.out.println(subOne);
System.out.println(subTwo);
System.out.println(subThree);
System.out.println(subFour);
System.out.println(subFive);
System.out.println(subSix);
Thread threadA = new ThreadA();
threadA.start();
while(guess != true){
System.out.print("Answer (Only one try): ");
int answer = sc.nextInt();
if (answer == finalAnswer){
guess = true;
}
}
}
}
Cheers for any help.
In order to implement Runnable you need to override the run() method (unless your class is abstract, which opens another discussion). What you have in your game class is run(int time), which won't count.
From the Runnable API:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
Bold added by me.

Java - static constructor

Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();

Categories

Resources