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;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The project is to create an application that models an ice cream shop, tracking the number of cartons opened and allowing two different scoop sizes, the professor wants it all split up into classes like I have it.
This is my main method, which creates and calls my scoop class.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
//Creating Objects
Scanner input = new Scanner(System.in);
Scoop scoop = new Scoop();
IceCreamShoppe icecreamshoppe = new IceCreamShoppe();
//Prompting user to define sizes of scoops and carton
System.out.println("How big is the first ice cream scoop?(radius in cm's)");
scoop.setScoop1(input.nextDouble());
System.out.println("How big is the second ice cream scoop?(radius in cm's)");
scoop.setScoop2(input.nextDouble());
System.out.println("How big is the ice cream carton?(radius in cm's)");
icecreamshoppe.setCarton_radius(input.nextDouble());
System.out.println("How big is the ice cream carton?(height in cm's)");
icecreamshoppe.setCarton_height(input.nextDouble());
//Returns to user their set values and sets size of carton
System.out.printf("Scoop 1: %.2f, Scoop 2: %.2f, Carton Radius: %.2f, Carton Height %.2f%n", scoop.getScoop1(), scoop.getScoop2(), icecreamshoppe.getCarton_radius(), icecreamshoppe.getCarton_height());
//While statement that continuously prompts user which scoop they want to use, everything else is done in the IceCreamShoppe Class
while(true) {
System.out.println("Which scoop would you like to use? (1 or 2) (0 = Exit)");
int scoopNumber = input.nextInt();
System.out.println("How many scoops would you like?");
int scoopCount = input.nextInt();
icecreamshoppe.serve(scoopNumber, scoopCount);
}//end while
}//end main
}//class
Here is my scoop method, that calls itself, I think this is the root of the problem. The problem is that my scoop sizes keep on getting reset whenever I call the scoop class.
public class Scoop {
//Instance Variables
private double volume;
private double scoop1;
private double scoop2;
//Constructors
public double doScoop(int r) {
System.out.printf("You want this%f", this.getScoop1());
if(r == 1) {
volume = (Math.PI)*Math.pow(this.getScoop1(), 3)*(4.0/3.0);
this.setVolume(volume);
System.out.printf("%f", volume);
return volume;
}
else if(r == 2) {
volume = (Math.PI)*Math.pow(this.getScoop2(), 3)*(4.0/3.0);
this.setVolume(volume);
System.out.printf("%f", volume);
return volume;
}
else {
System.out.println("Invalid Scoop Number!");
return 0;
}
}
/**
* #return the volume
*/
public double getVolume() {
return volume;
}
/**
* #param volume the volume to set
*/
public void setVolume(double volume) {
this.volume = volume;
}
/**
* #return the scoop1
*/
public double getScoop1() {
return scoop1;
}
/**
* #param scoop1 the scoop1 to set
*/
public void setScoop1(double scoop1) {
this.scoop1 = scoop1;
}
/**
* #return the scoop2
*/
public double getScoop2() {
return scoop2;
}
/**
* #param scoop2 the scoop2 to set
*/
public void setScoop2(double scoop2) {
this.scoop2 = scoop2;
}
//
}//end class
Here are the other two classes, I dont think they are the problem, but then again, what do I know?
import java.util.Scanner;
public class IceCreamShoppe {
//Instance Variables
private double carton_radius;
private double carton_height;
private int cartons_used = 0;
//Constructors
public IceCreamShoppe() {
}
public IceCreamShoppe(double r, double h) {
this.setCarton_radius(r);
this.setCarton_height(h);
}
public int carton_used() {
this.setCartons_used(this.getCartons_used() + 1);
return this.getCartons_used();
}
/*
* Object to serve the ice cream, the only input is which scoop is supposed to be used.
* #param s Sets the
*/
public boolean serve(int s, int n) {
Scanner input = new Scanner(System.in);
Scoop scoop = new Scoop();
Carton carton = new Carton();
int i = 0;
//Checks which scoop the is being used
if(s != 0) {
double scoopVolume = scoop.doScoop(1);
while(i <= n) {
if((boolean) carton.hasEnough(scoopVolume)) {
carton.remove(scoopVolume);
System.out.println(carton.getContains());
i++;
}
else {
this.carton_used();
carton.carton(this.getCarton_radius(), this.getCarton_height());
carton.remove(scoopVolume);
System.out.printf("Carton Empty, Total Cartons Used:%d%n", this.getCartons_used());
System.out.printf("New carton contains: %.2f%n", carton.getContains());
}
}
}
else {
System.out.printf("You have used %d cartons of ice cream, there is %.2f ice cream remaining in the current carton", this.getCartons_used(), carton.getContains());
return false;
}
return true;
}
//Getters and Setters
/**
* #return the carton_radius
*/
public double getCarton_radius() {
return carton_radius;
}
/**
* #param carton_radius the carton_radius to set
*/
public void setCarton_radius(double carton_radius) {
this.carton_radius = carton_radius;
}
/**
* #return the carton_height
*/
public double getCarton_height() {
return carton_height;
}
/**
* #param carton_height the carton_height to set
*/
public void setCarton_height(double carton_height) {
this.carton_height = carton_height;
}
/**
* #return the cartons_used
*/
public int getCartons_used() {
return cartons_used;
}
/**
* #param cartons_used the cartons_used to set
*/
public void setCartons_used(int cartons_used) {
this.cartons_used = cartons_used;
}
}//End Class
public class Carton {
//Instance Variables
private double contains;
//Objects
//Checks if the carton has enough remaining, if not
public boolean hasEnough(double v) {
if ((this.getContains() - v) >= 0) {
return true;
}
else {
return false;
} }
//Sets the carton size
public void carton(double r, double h) {
this.setContains(Math.PI*Math.pow(r, 2)*h);
}
//After checking if there is enough ice cream, this will run, there is
no check against going negative
public void remove(double v) {
this.setContains(this.getContains() - v);
}
//Getters and Setters
/**
* #return the contains
*/
public double getContains() {
return contains;
}
/**
* #param contains the contains to set
*/
public void setContains(double contains) {
this.contains = contains;
}
}
You are not passing in your scoop object into your icecreamshoppe.serve method and then you are creating a new scoop object in your serve method.
You should pass it in:
icecreamshoppe.serve(scoopNumber, scoopCount, scoop);
and change your serve method as follows:
public boolean serve(int s, int n, Scoop scoop) {
Scanner input = new Scanner(System.in);
Carton carton = new Carton();
int i = 0;
//Checks which scoop the is being used
if(s != 0) {
double scoopVolume = scoop.doScoop(1)
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.
I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}
if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year
In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD
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.