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.
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 want my program print all the entries in HashMap, and it does if I run the app in debugger. But if I run it normaly it prints only the last entry :(
Have no idea why it does,
Please help me.
MoneyCounter:
package home.lib;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import home.interfaces.GoodsOper;
import home.interfaces.WalletOper;
import home.interfaces.WastesListOper;
public class MoneyCounter implements WastesListOper, WalletOper, GoodsOper {
private ArrayList<String> wastesPrint = new ArrayList<>();
private Map<GregorianCalendar, Good> wastesMap = new HashMap<GregorianCalendar, Good>();
private Map<String, Good> goodsMap = new HashMap<String, Good>();
private Map<String, Wallet> walletsMap = new HashMap<String, Wallet>();
private Wallet currentWallet;
private Good currentGood;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
/**
* Provides selling (returning) of specified good puts the good
* to the wastesMap by date
* #param goodName
*/
#Override
public void sell(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
putMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Provides buying specified good puts the good you've bought
* to the wastesMap by date
* #param goodName
*/
#Override
public void buy(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
takeMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Add a new Wallet to the list if there is no the same one
* #param name
* #param currency
*/
#Override
public void createWallet(String name, String currency) {
walletsMap.putIfAbsent(name, new Wallet(name, currency));
}
/**
* Adds a new Good to the list with specified price
* #param name
* #param price
*/
#Override
public void createGood(String name, int price) {
goodsMap.putIfAbsent(name, new Good(name, price));
}
/**
* Returns array of strings with goods specifications, which
* satisfies the interval [startPrice, endPrice]
* #param startPrice
* #param endPrice
* #return array of strings String[]
*/
#Override
public String[] goodsListToStringByPrice(int startPrice, int endPrice) {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
if (e.getValue().getPrice() >= startPrice && e.getValue().getPrice() <= endPrice) {
goods[i++] = e.getValue().goodToString();
}
}
return goods;
}
/**
* Returns an array of Strings with goods descriptions
* #return array of strings String[]
*/
#Override
public String[] goodsListToString() {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
goods[i++] = e.getValue().goodToString();
}
return goods;
}
/**
* Replaces old Wallet's name with new one specified if one's name is absent
* #param oldName
* #param newName
*/
public void changeWalletName(String oldName, String newName) {
walletsMap.putIfAbsent(newName, new Wallet(newName, walletsMap.get(oldName)));
walletsMap.remove(oldName);
}
/**
* Returns an array of Strings with wallet descriptions
* #return array of strings String[]
*/
public String[] walletListToString() {
String[] wallets = new String[walletsMap.size()];
int i = 0;
for (Map.Entry<String, Wallet> e : walletsMap.entrySet()) {
wallets[i++] = e.getValue().walletToString();
}
return wallets;
}
/**
* Returns the wallet's money balance by name
* #param walletName
* #return String
*/
public String checkWallet(String walletName) {
return walletsMap.get(walletName).walletToString();
}
/**
* Deletes the wallet, specified by name from wallet list
* #param walletName
*/
#Override
public void delWallet(String walletName) {
walletsMap.remove(walletName);
}
/**
* Deletes the good, specified by name from good list
* #param goodName
*/
#Override
public void delGood(String goodName) {
goodsMap.remove(goodName);
}
/**
* Use this method to put more money to the wallet
* got payment for example
* #param count
*/
#Override
public void putMoney(int count) {
currentWallet.addMoney(count);
}
/**
* Use this method if you need money but not for buying a good
* #param count
*/
#Override
public void takeMoney(int count) {
currentWallet.getMoney(count);
}
/**
* Returns list of all wallets
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToString() {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
array.add(entry.getValue().walletToString());
}
return array;
}
/**
* Returns list of wallets specified by currency
* #param currency
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToStringByCurrency(String currency) {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
if (entry.getValue().getCurrency().equals(currency)) {
array.add(entry.getValue().walletToString());
}
}
return array;
}
/**
* Chooses wallet to operate with when you bus, sell, etc.
* #param walletName
*/
#Override
public void chooseTheWallet(String walletName) {
if (walletsMap.containsKey(walletName)) {
this.currentWallet = walletsMap.get(walletName);
}
}
/**
* Returns list of strings of all money wastes you've ever done
* #return ArrayList wastesPrint
*/
#Override
public void wastesListFillUp() {
for(Map.Entry<GregorianCalendar, Good> entry:wastesMap.entrySet()){
this.wastesPrint.add(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Is used for tests
* #throws IOException
*/
public void printAllList() throws IOException {
for (Map.Entry<GregorianCalendar, Good> entry : wastesMap.entrySet()) {
System.out.println(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Changes the specified good's price
* #param price
*/
#Override
public void changePrice(int price) {
currentGood.changePrice(price);
}
/**
* Chooses the good for operations
* #param goodName
*/
#Override
public void chooseTheGood(String goodName) {
if (goodsMap.containsKey(goodName)) {
this.currentGood = goodsMap.get(goodName);
}
}
}
Main:
package home.main;
import java.io.IOException;
import home.lib.MoneyCounter;
public class Main {
public static void main(String[] args) throws IOException {
MoneyCounter application = new MoneyCounter();
application.createGood("Snikers", 850);
application.createGood("Хрень какая-то", 1000);
application.createWallet("Основоной счет", "UAH");
application.chooseTheWallet("Основоной счет");
application.buy("Snikers");
application.buy("Хрень какая-то");
application.printAllList();
}
}
Wallet:
package home.lib;
public class Wallet {
// all money is kept
private int moneyCount;
private int debt;
private String currency;
private String name;
// constructor for new Wallet
public Wallet(String walletName, String currencyName) {
this.currency = currencyName;
this.moneyCount = 0;
this.debt = 0;
this.name = walletName;
}
// for renaming Wallet in WalletList
public Wallet(String walletName, Wallet oldWallet) {
this.name = walletName;
this.moneyCount = oldWallet.getMoneyCount();
this.debt = oldWallet.getDebt();
this.currency = oldWallet.getCurrency();
}
// actions with money
public void addMoney(int moneyCount) {
if (this.moneyCount >= 0 && this.debt == 0) {
this.moneyCount += moneyCount;
} else {
moneyCount -= this.debt;
this.debt = 0;
this.moneyCount = moneyCount;
}
}
public void getMoney(int moneyCount) {
if (this.debt == 0 && this.moneyCount > 0 && this.moneyCount >= moneyCount) {
this.moneyCount -= moneyCount;
} else {
moneyCount -= this.moneyCount;
this.moneyCount = 0;
this.debt += moneyCount;
}
}
// getters/setters block
public int getMoneyCount() {
return this.moneyCount;
}
public int getDebt() {
return this.debt;
}
public String getName() {
return this.name;
}
public String getCurrency() {
return this.currency;
}
public String walletToString() {
return this.debt <= 0 ? "("+this.name + " Остаток: " + (double)this.moneyCount/100 + " " + this.currency+")"
: "("+this.name + " Долг: -" + (double)this.debt/100 + " " + this.currency+")";
}
}
Good:
package home.lib;
public class Good {
private int price;
private String name;
public Good(String goodName, int goodPrice) {
this.name = goodName;
this.price = goodPrice;
}
public int getPrice() {
return this.price;
}
public double getPriceInDouble() {
return (double)this.price / 100;
}
public void changePrice(int price) {
this.price = price;
}
public String getName() {
return this.name;
}
public String goodToString() {
return "Товар: " + this.name + " | Цена: " + (double) this.price / 100;
}
}
I've got an answer. I used GregorainCalendar as a HashMap key. So, when I was starting program normaly, it was done in no time. So it was adding different values for ONE key. When you run the program in debugger you can't press next step 10 times in one moment so the time is different, so the keys are different too, so it returns all entries.
Be attentive when use time and all will be Ok :)
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.
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.
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?
}