So I have to create a Bank Simulator project for class, and so far I have a few of the methods implemnted. But currently I am having trouble with the doBusiness method in the ServiceCenter class. Here is the code I have so far.
Main: BankSimulator
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What is the time duration (in minutes) to be simulated? ");
int maxTime = input.nextInt();
System.out.print("What percentage of the time (0-100) does a customer arrive? ");
int arrivalProb = input.nextInt();
ServiceCenter bank = new ServiceCenter();
while (bank.getTime() <= maxTime || bank.customersRemaining()) {
if (bank.getTime() <= maxTime && customerArrived(arrivalProb)) {
bank.addCustomer();
}
bank.doBusiness();
}
//bank.displayStats();
}
private static boolean customerArrived(int prob)
{
return (Math.random()*100 <= prob);
}
}
Server class:
public class Server {
private static int nextID = 1;
private int serverID;
private int endTime;
private Customer serving;
public Server()
{
serverID = nextID;
nextID++;
endTime = 0;
serving = null;
}
/**
* Accessor method for getting the server ID number.
* #return the server ID
*/
public int getID()
{
return serverID;
}
/**
* Assigns a customer to the server and begins the transaction.
* #param c the new customer to be served
* #param time the time at which the transaction begins
*/
public void startCustomer(Customer c, int time)
{
serving = c;
endTime = time + c.getJobLength();
}
/**
* Accessor method for getting the current customer.
* #return the current customer, or null if no customer
*/
public Customer getCustomer()
{
return serving;
}
/**
* Identifies the time at which the server will finish with
* the current customer
* #return time at which transaction will finish, or 0 if no customer
*/
public int busyUntil()
{
return endTime;
}
/**
* Finishes with the current customer and resets the time to completion.
*/
public void finishCustomer()
{
serving = null;
endTime = 0;
}
}
Customer class:
import java.util.Random;
public class Customer {
private static final int MAX_LENGTH = 8;
private static final Random rand = new Random();
private static int nextID = 1;
private int customerID;
private int arrivalTime;
private int jobLength;
/**
* Constructs a customer with the next available ID number,
* the specified arrival time, and a random job length.
* #param arrTime the time at which the customer arrives
*/
public Customer(int arrTime)
{
customerID = nextID;
nextID++;
arrivalTime = arrTime;
jobLength = rand.nextInt(MAX_LENGTH)+1;
}
/**
* Accessor method for getting the customer's ID number.
* #return the customer ID
*/
public int getID()
{
return customerID;
}
/**
* Accessor method for getting the customer's arrival time.
* #return the time at which the customer arrived
*/
public int getArrivalTime()
{
return arrivalTime;
}
/**
* Accessor method for getting the length of the job
* #return the job length (in minutes)
*/
public int getJobLength()
{
return jobLength;
}
}
I had to create the following class called ServiceCenter where getTime returns the time in the simulation which starts at 0 and increments on each step. An addCustomer method where we add a customer to the queue and displayed a message. A customerRemaining which returns true if a customer is currently being waited on. Lastly the doBusiness method which increments the time, if the server finished with a customer remove them from the queue, and if the server is free and there is a customer in the queue, begin serving them. I have the first few ones done except the doBusiness method I am stuck on. Does anyone have any tips?
The code listed above was created by Dave Reed and I take no credit for the code.
ServiceCenter class:
import java.util.LinkedList;
import java.util.Queue;
public class ServiceCenter {
private int arrivalTime, departureTime;
private Queue <Customer> customer;
private Server server;
public ServiceCenter()
{
server = new Server();
customer = new LinkedList <Customer> ();
}
public String addCustomer ()
{
Customer customer1 = new Customer (arrivalTime);
customer.add(customer1);
String result = "" + customer1.getArrivalTime() + "" + customer1.getID() + "" + customer1.getJobLength();
return result;
}
public void doBusiness()
{
if(!customer.isEmpty())
{
if(server == null)
{
customer.remove();
}
}
}
public int getTime()
{
return departureTime - arrivalTime;
}
public boolean customersRemaining()
{
if (!(customer.isEmpty()))
return true;
else
return false;
}
}
Any help at all or tips would be greatly appreciated. I've been trying to figure it out for a week now, but for some reason queues are my weakness. Thanks for reading and sorry for it being so long. Just wanted it to be detailed.
You are using new Customer (arrivalTime); but you don't have the arrivalTime in your constructor of the ServiceCenter-class.
Related
I was experimenting with a program idea and therefore have way to many classes, which very well could have been methods, however in my CF method (Don't worry about the naming conventions they were changed to post online) however, when I try to set cF to cF=getTi-getTe the values from the getters always print 0 but this is only in the calculate cF method. If I print the getters and setters in the main method alone they print out with the correct numbers.
public class CF {
private double cF;
Income rI= new Income();
Expenses e = new Expenses();
public double getCF() {
return cF;
}
public void setCF(double cF) {
this.cF = cF;
}
public CF(){
//cF=0;
}
public double calculateCF(){
cF= rI.getTi()-e.getTe();// this line will return 0 no matter what
return cF;
}
}
public class Expenses {
private double tExpenses,exp1,exp2;
public Expenses(){
tExpenses=exp1=exp2=0;
}
public double calculateTotalExpenses(){
tExpenses=exp1+exp2;
return tExpenses;
}
/**
* #return the tExpenses
*/
public double getTe() {// again don't worry about naming conventions //they are correct in the IDE
return tExpenses;
}
/**
* #param tExpenses the tExpenses to set
*/
public void setTe(double tExpenses) {
this.tExpenses = tExpenses;
}
}
public class RI {
private double rI;
private double incomeMisc;
private double tIncome;
public RI(){
rI=0;
incomeMisc=0;
tIncome=0;
}
public double calculateRI(){
tIncome= rI+incomeMisc;
return tIncome;
}
/**
* #return the incomeMisc
*/
public double getIncomeMisc() {
return incomeMisc;
}
/**
* #param incomeMisc the incomeMisc to set
*/
public void setIncomeMisc(double incomeMisc) {
this.incomeMisc = incomeMisc;
}
/**
* #return the tIncome
*/
public double gettIncome() {
return tIncome;
}
/**
* #param tIncome the tIncome to set
*/
public void settIncome(double tIncome) {
this.tIncome = tIncome;
}
}
public class FSAProgram {
public static void main(String[] args) {
RI rI = new RI();
Expenses e = new Expenses();
CF cF= new CF();
System.out.println("Enter RI");
Scanner k = new Scanner(System.in);
rI.I(k.nextDouble());
System.out.println("Enter Misc Income");
rI.setIncomeMisc(k.nextDouble());
rI.calculateRI();
System.out.println("Total Income is: "+ rI.getTi());
System.out.println("Enter expense");
e.setExp1(k.nextDouble());// I know this isn't correct its because // I changed the name to post this question
e.calculateTotalExpenses();
System.out.println("Total Expenses :"+ e.gettExpenses());
//cF.calculateCF();
System.out.println(""+(e.gettExpenses() +" "+ rI.gettIncome()));
// Prints fine when last statement is executed
//The next statement is what returns 0 unfortunately
System.out.println("CF: "+ cF.calculateCF());
}
}
Sample output
**Enter RI
2000
Enter Misc Income
0
Total Income is: 2000.0
Enter Exp1// these are a combination of other things in the actual program
900
Total Expenses :900.0
900 2000
CF 0.0
You just make two new objects without setting its value, sure it returns 0.
Income rI= new Income();
Expenses e = new Expenses();
To make it workable, here are hints:
//in your main
CF cF= new CF(rI, e);
//in your cf
private double cF;
private Income income;
private Expenses expense;
public CF(Income rI, Expense e){
this.income = rI;
this.expense = e;
}
I've got 2 classes: Deadline and Task. Within the Task class, I want to create an extendDeadline method where it increases the deadline of a task. I tried the following:
public void extendDeadline(int extend){
deadline = deadline + extend;
}
but this didn't work because the type of deadline is Deadline. Can anyone help me?
Code for deadline class:
import java.text.DateFormat;
import java.util.Date;
public class Deadline {
// dates are stored as the number of seconds since 01/01/1970
private long deadline;
// we have a DateFormat to format the date as text
private DateFormat dateFormatter;
// define some constants...
public static final long SECOND = 1000;
public static final long MINUTE = SECOND*60;
public static final long HOUR = MINUTE * 60;
public static final long DAY = HOUR*24;
public static final long WEEK = DAY*7;
/**
* Construct a new deadline.
* By default, deadlines are one week ahead of the time now.
*/
public Deadline() {
// by default you get a week
deadline = now() + WEEK;
dateFormatter = DateFormat.getDateInstance();
}
/**
* #return the time now as a long
*/
private long now() {
return new Date().getTime();
}
/**
* Get the date of this deadline as a Date object.
* #return the date of this deadline as a Date object.
*/
private Date getDeadlineDate() {
return new Date(deadline);
}
/**
* Change the date of this deadline by a specified number of days.
* #param numDays the number of days to add to the deadline date (may be negative).
*/
public void setNewDeadline(int numDays) {
deadline = deadline + (DAY*numDays);
}
/**
* Find out if this deadline has passed.
* #return true when the time now is later than the deadline.
*/
public boolean hasPassed() {
return now() > deadline;
}
/**
* Return this deadline formatted as text to be printed.
* #return a string representation of this deadline.
*/
#Override
public String toString() {
return dateFormatter.format(getDeadlineDate());
}
#Override
public boolean equals(Object o) {
if (o instanceof Deadline) {
Deadline other = (Deadline) o;
if (this.toString().equals(other.toString())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
code for task class:
public class Task {
private int id;
private String description;
private Deadline deadline;
private boolean done;
private int estimatedLength;
private int hoursWork;
/**
* Constructor for objects of class Task
*/
public Task(int id , String description, int estimatedLength) {
this.description = description;
this.id = id;
this.estimatedLength = estimatedLength;
deadline = new Deadline();
done = false;
hoursWork = hoursWork;
}
public int getId(){
return id;
}
public Deadline getDeadline(){
return deadline;
}
public String getDescription(){
return description;
}
public boolean isDone(){
return done;
}
public double getPercentageComplete(){ //make sure this is right
double result = 0;
double hoursWorkDouble = (double) hoursWork;
double estimatedLengthDouble = (double) estimatedLength;
result = (double) hoursWork / (double) estimatedLength * 100.0;
System.out.println("Percentage complete: "+result);
return result;
}
public boolean isLate(){
if(done = false) { // dont forget to put AND date greater deadline
return true;
} else{
return false;
}
}
public void setDone(){
this.done = true;
}
public void extendEstimate(int extendEstimate){
estimatedLength = estimatedLength + extendEstimate;
/*int extendEstimate= 0;
int estimatedLength= 0;
int result= extendEstimate + estimatedLength;
System.out.println(+result);
*/
}
public void recordHoursWorked(int recordHours){
hoursWork= hoursWork + recordHours;
}
public void extendDeadline(int extend){
}
}
It looks like you have an setNewDeadline(int numDays) method in your Deadline class. (this should probably be renamed to something like extendDeadlineByDays because you're not resetting the deadline, just extending it) It looks like what you actually want to do is call that method. So, in the Task class, the method should look like this:
public void extendDeadline(int extend){
deadline.setNewDeadline(extend);
}
In this case you're updating the deadline, rather than trying to reassign it. What you were trying to do was take a Deadline, and add an int to it, which is impossible.
Here is my problem I can't seem to figure out how to invoke a ParkingTicket object if (carMinutesPaid>meterMinutesPaid)? can any one help here are the details below to the question.
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
System.out.println("null");
}
return new ParkingTicket(parker, parkee);
}
Here is the question for my project.
Remember, this method must be able to be used without a ParkingTicket object in existence.
Using a Car parameter and a ParkingMeter parameter, decide whether a ParkingTicket object should be created.
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and return the result.
Return null if a ticket was not merited.
Here is my car class:
/**
* This is a Car class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class Car
{
private static final int MINIMUM_PLATE_LENGTH=2;
private static final int MAXIMUM_PLATE_LENGTH=7;
public static final char MANUAL_TRANSMISSION='m';
public static final char AUTOMATIC_TRANSMISSION='a';
private static int defaultMinutesParked = 0;
private static double defaultOdometerInKm = 50000.5;
private String licensePlate;
private char transmissionType;
private double odometerInKm;
private int minutesParked;
/**
* #param newProposedLicensePlate the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public Car(String newProposedLicensePlate)
{
setLicensePlate(newProposedLicensePlate);
transmissionType = AUTOMATIC_TRANSMISSION;
odometerInKm = defaultOdometerInKm;
minutesParked = defaultMinutesParked;
}
/**
* #return the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public String getLicensePlate()
{
return licensePlate;
}
/**
* #return the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
*/
public char getTransmissionType()
{
return transmissionType;
}
/**
* #return the odometer in kilometers
*/
public double getOdometerInKm()
{
return odometerInKm;
}
/**
* Recieve the license plate
* Mutator.licensePlate.
* #param proposedLicense String Conforming to ICBC *length* guidlines:
* http://www.icbc.com/vehicle-registration/license-plates/Pages/Personalized-licence-plates.aspx
* May also be null. The null represents a car without a plate
* If validation fails, null will be set.
*/
public void setLicensePlate(String proposedLicense)
{
if(proposedLicense==null){
licensePlate = proposedLicense;
}
else if(proposedLicense.length()>=MINIMUM_PLATE_LENGTH && proposedLicense.length()<=MAXIMUM_PLATE_LENGTH){
licensePlate = proposedLicense;
}
else{
licensePlate = null;
}
}
/**
* #param mOrA recieve the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
* if invalid type of transmission is entered then will return "Installation failure: 'mOrA' is not a vaild transmission type"
*/
public void setTransmissionType(char mOrA)
{
if(mOrA==MANUAL_TRANSMISSION){
transmissionType = mOrA;
}
else if(mOrA==AUTOMATIC_TRANSMISSION){
transmissionType = mOrA;
}
else if (mOrA==mOrA){
System.out.println("Installation failure:" + " " + ("'")+(mOrA)+("'") + " " + "is not a valid transmission type.");
}
else{
transmissionType = mOrA;
}
}
/**
* #return the value of the odometer in with the String kilometers
*/
public String readOdometer()
{
return odometerInKm + " " + "kilometers";
}
/**
* #return the false if the minutesParked equals zero; otherwise true
*/
public boolean isParked()
{
if(minutesParked==defaultMinutesParked){
return false;
}
else{
return true;
}
}
/**
* #param duration replaces any existing value in minutesParked with the value from duration
*/
public void park(int duration)
{
if(duration>=defaultMinutesParked){
minutesParked = duration;
}
}
/**
* #param aOdometerInKm recieve the odometer in kilometers
*/
public void setOdometerInKm(double aOdometerInKm)
{
odometerInKm = aOdometerInKm;
}
/**
* #param aMinutesParked recieve the minutes parked in the stall but can not be a negative number
* if invalid number of minutes is entered then the number of minutes will not change.
*/
public void setMinutesParked(int aMinutesParked)
{
if(aMinutesParked>=defaultMinutesParked){
minutesParked = aMinutesParked;
}
else{
return;
}
}
/**
* #return the minutes parked
*/
public int getMinutesParked()
{
return minutesParked;
}
}
here is my ParkingMeter class:
/**
* This is a ParkingMeter class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class ParkingMeter
{
private int minutesPaid;
private String methodPaid;
/**
* #param newMinutesPaid the minutes paid for parking meter
*/
public ParkingMeter()
{
}
/**
* #return the minutes paid
*/
public int getMinutesPaid()
{
return minutesPaid;
}
/**
* #return the method paid
*/
public String getMethodPaid()
{
return methodPaid;
}
/**
* #param paidBy the payment method customer will paid by
*/
public void setMethodPaid(String paidBy) /* BONUS for creating method paid */
{
if(methodPaid=="Visa"){
methodPaid = paidBy;
}
else if(methodPaid=="Master Card"){
methodPaid = paidBy;
}
else if(methodPaid=="American Express"){
methodPaid = paidBy;
}
else if(methodPaid=="Cash"){
methodPaid = paidBy;
}
else if(methodPaid=="Debit"){
methodPaid = paidBy;
}
else{
methodPaid = paidBy;
}
}
/**
* #param quantity the added minutes paid must not have a negative number
*/
public void addMinutesPaid(int quantity)
{
if(quantity>=0){
minutesPaid+=quantity;
}
}
}
and here is my ParkingTicket class:
/**
* This is a ParkingTicket class for Impark.
*
* #author Tre
* #version 1.0
*/
public class ParkingTicket
{
private final String referenceNumber;
private static String carLicensePlate;
private static int carMinutesParked;
private static int meterMinutesPaid;
private static int count = 1000;
private static String PREFIX = "V";
/**
* #param recorededLicense the value of the tick number
*/
private ParkingTicket(String recordedLicense, int newCarMinutesParked, int newMeterPaidMinutes)
{
referenceNumber = (PREFIX+count++);
carMinutesParked = newCarMinutesParked;
meterMinutesPaid = newMeterPaidMinutes;
}
/**
* #param
*/
private ParkingTicket(Car parker, ParkingMeter parkee)
{
this(parker.getLicensePlate(), parker.getMinutesParked(), parkee.getMinutesPaid());
}
/**
* #return referenceNumber the reference number
*/
public String getReferenceNumber()
{
return referenceNumber;
}
/**
* #return carLicensePlate the car's license plate
*/
public String getCarLicensePlate()
{
return carLicensePlate;
}
/**
* #return carMinutesParked the minutes car was parked
*/
public int getCarMinutesParked()
{
return carMinutesParked;
}
/**
* #return meterMinutesPaid the minutes paid on meter
*/
public int getMeterMinutesPaid()
{
return meterMinutesPaid;
}
/**
* #return count the with initial value of 1000
*/
public int getCount()
{
return count;
}
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
return null;
}
return new ParkingTicket(parker, parkee);
}
}
This requirement:
Using a Car parameter and a ParkingMeter parameter, decide whether a
ParkingTicket object should be created.
suggests that you provide two parameters to the checkParking method, one is of the type Car and one of the ParkingMeter. So it should be like so:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
This code :
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
won't even compile
line 1: you're trying to assign int to object - that's called type mismatch.
line 2: variable parkee is not declared anywhere (except for the headline of the question).
You see, only the Car object holds the information about the parking duration, and you need the object for creating parking ticket. Same for the ParkingMeter
It should be vice versa - you get the values from the objects:
int carMinutesParked = car.getMinutesParked();
int meterMinutesPaid = meter.getMinutesPaid();
and proceed from here with if( or even use it in if without declaring temporary variables).
This one:
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and
return the result.
you did OK.
Now this requirement:
Return null if a ticket was not merited.
suggest the method will return null, not string that equals to "null" .
So, based on these requirements it should rather be:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
{
//sanity check (bonus)
if ((car == null) || (meter == null))
return null;
if(car.getMinutesParked() > meter.getMinutesPaid()){
return new ParkingTicket(car, meter);
}
return null;
}
Note however, I don't know if you need any additional logic in this code and don't suggest this should be your final version, just explaining the general approach.
hello I get the error message: Missing Method Body Or Declare Abstract, how to fix this, what does this mean?
my code:
public class Mobile
{
// type of phone
private String phonetype;
// size of screen in inches
private int screensize;
// memory card capacity
private int memorycardcapacity;
// name of present service provider
private String mobileServiceProvider;
// type of contract with service provider
private int mobileTypeOfContract;
// camera resolution in megapixels
private int cameraresolution;
// the percentage of charge left on the phone
private int chargeUp;
// wether the phone has GPS or not
private int switchedOnFor;
// to simulate using phone for a period of time
private int charge;
// checks the phones remaining charge
private String provider;
// simulates changing the provider
private String GPS;
// instance variables - replace the example below with your own
private int cost;
// declares cost of the item
// The constructor method
public Mobile(String mobilephonetype, int mobilescreensize,
int mobilememorycardcapacity, String mobileServiceProvider, int mobileTypeOfContract, int mobilecameraresolution, String mobileGPS, int chargeUp,int switchedOnFor, String changeProvider,int getBalance, int cost,int price) {
// initialise the class attributes from the one given as parameters in your constructor.
}
/**
* Other constructor
*/
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
/**
*returns a field price.
*/
public int getcost()
{
return balance;
}
/**
*return the amount of change due for orders of mobiles.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
*/
public void cost (int price)
{
balance = balance + amount;
}
//this.serviceprovider = newserviceprovider;
//this.typeofcontract = 12;
//this.checkcharge = checkcharge;
//this.changeProvider = giffgaff;
//Mobile samsungPhone = new Mobile(
// "Samsung" // String mobilephonetype
//, 1024 // intmobilescreensize
//, 2 // intmobilememorycardcapacity
//, 8 // intmobilecameraresolution
//, "GPS" //String mobileGPS
//, "verizon" // String newserviceprovider
//, "100" // intchargeUp
//, "25" // intswitchedOnFor
//, "25" // intcheckCharge
//, "giffgaff"// String changeProvider
//);
//typeofcontract = 12;
//checkcharge = checkcharge;
//Mutator for newserviceprovider
public void setmobileServiceProvider(String newmobileServiceProvider)
{
mobileServiceProvider = newmobileServiceProvider;
}
//Mutator for contracttype
public void setmobileTypeOfContract(int newmobileTypeOfContract)
{
mobileTypeOfContract = newmobileTypeOfContract;
}
//Mutator for chargeUp
public void setchargeUp(int chargeUp)
{
this.chargeUp = chargeUp;
}
//Mutator to simulate using phone for a period of time
public void switchedOnFor(int switchedOnFor)
{
this.switchedOnFor = switchedOnFor;
}
//Accessor for type of phone
public String getType()
{
return phonetype;
}
//Accessor for provider
public String getprovider()
{
return mobileServiceProvider;
}
//Accessor for contract type
public int getContractType()
{
return mobileTypeOfContract;
}
//Accessor for charge
public int getCharge()
{
return chargeUp;
}
//Accessor which checks the phones remaining charge
public int checkCharge()
{
return checkCharge;
}
// simulates changing the provider
public void changeProvider()
{
provider = changeProvider;
}
//returns the amount of change due for orders of mobiles.
public int Balance()
{
return balance;
}
// A method to display the state of the object to the screen
public void displayMobileDetails() {
System.out.println("phonetype: " + phonetype);
System.out.println("screensize: " + screensize);
System.out.println("memorycardcapacity: " + memorycardcapacity);
System.out.println("cameraresolution: " + cameraresolution);
System.out.println("GPS: " + GPS);
System.out.println("mobileServiceProvider: " + mobileServiceProvider);
System.out.println("mobileTypeOfContract: " + mobileTypeOfContract );
}
/**
* The mymobile class implements an application that
* simply displays "new Mobile!" to the standard output.
*/
public class mymobile {
public void main(String[] args) {
System.out.println("new Mobile!"); //Display the string.
}
}
public static void buildPhones(){
Mobile Samsung = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
Mobile Blackberry = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
}
public static void main(String[] args) {
buildPhones();
}
}
any answers or replies and help would be greatly appreciated as I cant get it to compile like it did before with no syntax errors.
Check constructor declared on line 42. It doesn't have a body.
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Additionally, price and a number of other fields are not declared anywhere.
remove ; from
public Mobile (int cost); {
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Here, you left a semicolon, delete it.
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
I am doing a observer pattern as a homework but i am failing the Test.
I have been stacked for quite a while. If you could have a look at my code and give me an advice where I am wrong and what I am not doing as supposed. Cheers. Here is the code.
public class Share
{
/**#param poundsAndPences stores the monetary unit for the share.
* #unique a instance of the Share class responsible for the observer pattern*/
private double poundsAndPences = 1.00;
ArrayList<ShareWatcher> list = new ArrayList<ShareWatcher>();
public boolean addShareWatcher(ShareWatcher sw)
{
list.add(sw);
if (list.contains(sw))
{
return true;
}
return false;
}
public boolean removeShareWatcher(ShareWatcher sw)
{
if(list.contains(sw))
{
list.remove(sw);
return true;
}
else
{
return false;
}
}
/** Share(double poundsAndPences) private constructor.
* 1-st pre-requisite for the multiple pattern
* takes and double value and initialized the local
* variable with the one that have been passed
* #param poundsAndPences sets the local variable with the current value*/
Share()
{
// this.poundsAndPences = poundsAndPences;
// changeState();
// System.out.println("test: " + list);
}
/**getPoundsAndPences() is a getter method to.
* #return the poundsAndPences
*/
public double getPrice()
{
return poundsAndPences;
}
/**setPoundsAndPences(int poundsAndPences) is a mutator method.
* #param poundsAndPences set the poundsAndPences passed to the
* methods to the local ones
*/
public void setPrice(double poundsAndPences)
{
this.poundsAndPences = poundsAndPences;
changeState();
updateShareWatcher();
}
public void changeState()
{
poundsAndPences = getPrice() ;
}
public void updateShareWatcher()
{
// System.out.println("list: " + list);
int counter = 0;
for(ShareWatcher sw: list)
{
// System.out.println("list test: "+ counter++ + " %%% " + sw);
sw.updatePrice(poundsAndPences);
// System.out.println(list.toString());
}
}
}
this is the interface
public interface ShareWatcher
{
void updatePrice(double price);
}
public class BankManager implements ShareWatcher
{
int portfolio = 0;
/**
* Buy value for bank manager.
*/
static double BM_BUY = 1.00;
/**
* Sell value for bank manager.
*/
static double BM_SELL = 4.00;
/**
* Increment value for bank manager.
*/
static int BM_INCREMENT = 100;
public BankManager(double BM_BUY, double BM_SELL, int BM_INCREMENT)
{
this.BM_BUY = BM_BUY;
this.BM_SELL = BM_SELL;
this.BM_INCREMENT = BM_INCREMENT;
portfolio = 0;
// updatePrice(portfolio);
}
public int getPortfolio()
{
return portfolio;
}
public void setPortfolio(int portfolio)
{
this.portfolio = portfolio;
// updatePrice(portfolio);
}
public void updatePrice(double price)
{
if(price < 1.00)
{
BM_BUY = price;
System.out.println("BankManager buy shares at: " + BM_BUY);
}
if(price > 4.00)
{
BM_SELL = price;
System.out.println("BankManager sell shares at:" + BM_SELL);
}
// portfolio = price;
// System.out.println("Update BankManager");
// System.out.println("New value is: " + portfolio);
}
}
public class StockBroker implements ShareWatcher
{
int portfolio = 1;
/**
* Buy value for stock broker.
*/
static double SB_BUY = 2.00;
/**
* Sell value for stock broker.
*/
static double SB_SELL = 3.00;
/**
* Increment value for stock broker.
*/
static int SB_INCREMENT = 500;
StockBroker(double SB_BUY, double SB_SELL, int SB_INCREMENT)
{
// this.price = portfolio;
// updatePrice(portfolio);
this.SB_BUY = SB_BUY;
this.SB_SELL = SB_SELL;
this.SB_INCREMENT = SB_INCREMENT;
portfolio = 0;
// updatePrice(portfolio);
}
public int getPortfolio()
{
return portfolio ;
}
public void setPortfolio(int portfolio)
{
this.portfolio = portfolio;
}
public void updatePrice(double price)
{
// StockBroker sb = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
if(price < 2.00)
{
SB_BUY = price;
System.out.println("StockBroker buy shares at: " + SB_BUY);
}
if(price > 3.00)
{
SB_SELL= price;
System.out.println("StockBroker sell shares at:" + SB_SELL);
}
portfolio = SB_INCREMENT;
// System.out.println("Update StockBroker");
// System.out.println("New value is: " + portfolio);
}
}
and here is the testing class
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;
/** A set of unit tests that check the solution to the SILVER task.
*
*/
public class ShareTest {
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE1 = 4.01;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE2 = 0.99;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE3 = 2.12;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE4 = 1.89;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE5 = 1.83;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE6 = 2.78;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE7 = 14.12;
/**
* Arbitrary stock price value for testing.
*/
final static double PRICE8 = 6.99;
/**
* Buy value for bank manager.
*/
final static double BM_BUY = 1.00;
/**
* Sell value for bank manager.
*/
final static double BM_SELL = 4.00;
/**
* Increment value for bank manager.
*/
final static int BM_INCREMENT = 100;
/**
* Buy value for stock broker.
*/
final static double SB_BUY = 2.00;
/**
* Sell value for stock broker.
*/
final static double SB_SELL = 3.00;
/**
* Increment value for stock broker.
*/
final static int SB_INCREMENT = 500;
public ShareTest(){
}
#Test
public void testChangePrice1() {
final Share share = new Share();
final BankManager bankManager = new BankManager(BM_BUY, BM_SELL, BM_INCREMENT);
final StockBroker stockBroker = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
assertTrue(share.addShareWatcher(bankManager));
assertTrue(share.addShareWatcher(stockBroker));
share.setPrice(PRICE5);
final int expectedValue1 = 0;
// System.out.println("*****BankManager " + bankManager.getPortfolio());
assertEquals(bankManager.getPortfolio(), expectedValue1);
final int expectedValue2 = 500;
System.out.println("*****StockBroker " + stockBroker.getPortfolio());
assertEquals(stockBroker.getPortfolio(), expectedValue2);
}
/**
* Test of changePrice method, of class Share. A similar test to above. More
* changes this time.
*/
// #Ignore
#Test
public void testChangePrice2() {
final Share share = new Share();
final BankManager bankManager = new BankManager(BM_BUY, BM_SELL, BM_INCREMENT);
final StockBroker stockBroker = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
assertTrue(share.addShareWatcher(bankManager));
assertTrue(share.addShareWatcher(stockBroker));
share.setPrice(PRICE3);
share.setPrice(PRICE6);
share.setPrice(PRICE8);
final int expectedValue1 = 0;
assertEquals(bankManager.getPortfolio(), expectedValue1);
final int expectedValue2 = 0;
assertEquals(stockBroker.getPortfolio(), expectedValue2);
}
/**
* Test of changePrice method, of class Share. A similar test to above. More
* changes this time.
*/
// #Ignore
#Test
public void testChangePrice3() {
final Share share = new Share();
final BankManager bankManager = new BankManager(BM_BUY, BM_SELL, BM_INCREMENT);
final StockBroker stockBroker = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
assertTrue(share.addShareWatcher(bankManager));
assertTrue(share.addShareWatcher(stockBroker));
share.setPrice(PRICE1);
share.setPrice(PRICE4);
share.setPrice(PRICE7);
share.setPrice(PRICE2);
final int expectedValue1 = 100;
assertEquals(bankManager.getPortfolio(), expectedValue1);
final int expectedValue2 = 500;
assertEquals(stockBroker.getPortfolio(), expectedValue2);
}
}
Switch assertEquals(..., exptedValue); to assertEquals(exptedValue, ...);. This doesn't change your failures, but follows the javadoc at Class Assert and fixes the reported output.
In BankManager, you never change portfolio, so this is the reason for your first failure.
In StockBroker, you set portfolio always to SB_INCREMENT, so this might be the reason for your second failure.
So in order for this to work, you must either adjust the portfolio, if the price changes or adjust the expectedValues to your current implementation.