First off, I need to override the method:
public boolean recordBid(int bidPrice, String sellerID)
so it manages the recording of a bid.
To begin with, if the bidPrice is greater than the buyNowprice then this bidPrice should reset to the buyNowPrice. After the bid price has been reset (if required) the method should invoke the superclass version of the recordBid() method, passing along the bid price and seller ID as parameters, and trap the result that it returns (ie. store it in a variable), so that it can be checked to determine if the bid price has been recorded successfully.
Im a little confused on how I need to trap the result and also not sure if Im doing it the right way here?.
My original recordBid() method:
public boolean recordBid(int bidPrice, String bidderID)
{
if (saleEnded == true)
{
return false;
}
else if (bidPrice <= this.highestBid)
{
return false;
}
else
{
this.highestBid = bidPrice;
this.bidderID = bidderID;
return true;
}
}
My subclass, where I need to overwrite recordBid()
public class BuyItNowSale extends ItemSale {
//instance variables
private double buyNowPrice;
private boolean acceptingNearestOffer;
public BuyItNowSale(String itemNumber, String itemDescription, String itemCondition,
String sellerID, boolean acceptingNearestOffer) {
super(itemNumber, itemDescription, itemCondition, sellerID);
this.acceptingNearestOffer = false;
//overidden recordBid() method
public boolean recordBid(int bidPrice, String bidderID) {
if(bidPrice > buyNowPrice) {
bidPrice = 0;
super.recordBid(bidPrice, sellerID);
}
}
With your requirement
if the bidPrice is greater than the buyNowprice then this bidPrice should reset to the buyNowPrice
Your method should be:
#Override
public boolean recordBid(int bidPrice, String bidderID) {
if(bidPrice > buyNowPrice) {
bidPrice = (int) buyNowPrice;
}
return super.recordBid(bidPrice, sellerID);
}
Related
I want to create the below class
associatename:String
workstatus:String
associate() :constructor
getassociatename():String
setassociatename(String):void
getworkstatus()String
tracksassociatestatus():int
setworkstatus(String):void
The trackAssociateStatus method takes the number of days as argument and sets the work status of the associate based on the number of days. The first 20 days they learn “C”, the next 20 days they learn “Java” In the Main class invoke the trackAssociateStatus method and find the work status and display the output.
output:The associate abc work status:Project phase
I tried this....But i got error
//associate class
public class associate{
private int associatename;
private String workstatus;
private int days;
void associate()
{
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus();
setworkstatus();
}
public int getassociatename()
{
return associatename;
}
public void setassociatename(int associatename)
{
this.associatename=associatename;
}
public String getworkstatus()
{
return workstatus;
}
public void tracksassociatestatus(int days)
{
if(days<20)
setworkstatus("C");
else
setworkstatus("Java");
}
public void setworkstatus(String workstatus)
{
this.workstatus=workstatus;
}
}
//main class
associate a =new associate();
Scanner in=new Scanner(System.in);
int associateid=0;
String workstatus=null;
int days=0;
System.out.println("Enter the associateid:");
associateid=in.nextInt();
a.associateid=(associateid);
System.out.println("Enter the no of days:");
days=in.nextInt();
a.trackassociatestatus();
System.out.println("The id is "+a.getassocaiteid()+" work status "+a.getworkstatus());
Based on your (seemingly) UML spec, your class would look like the following:
public class Associate {
private String associateName;
private String workStatus;
public Associate() {
// This constructor is optional, a no-args constructor is added by the compiler to any class not explicitly naming a constructor.
}
public String getAssociateName() {
return associateName;
}
public void setAssociateName(String associateName) {
this.associateName = associateName;
}
public String getWorkStatus() {
return workStatus;
}
public void setWorkStatus(String workStatus) {
this.workStatus = workStatus;
}
public int tracksAssociateStatus() {
// TODO write logic here
return 1; // TODO change to whatever you need to return
}
}
You were specifying int for getAssociateName, when associateName is a String. This won't work; you need your getter return type to be the same as your field data type, or you need to convert the data to the method's return type. (The former is best practice).
Constructors don't specify a type, the class name is used and the compiler will understand what you want to do (which is return a new instance of the class). Therefore, your void associate() will tell the compiler "create a method called associate that doesn't return anything".
Well, would be nice if you provide the error itself for us.
But meanwhile, have you notice that your tracksassociatestatus method recieves an integer parameter days, and your constructor passes nothing to it?
So try changing your constructor to be something like:
Public associate() {
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus(10);
setworkstatus();
}
For a cleaner code, check the other answer.
If you still have errors, please share them.
import java.util.*;
public class Associate
{
private String associateName;
private int workStatus;
private int days;
Scanner sc = new Scanner(System.in);
public String getAssociateName()
{
System.out.println("Enter the Associate id:");
associateName = sc.nextLine();
return associateName;
}
public void setassociatename(int associatename)
{
this.associateName=associateName;
}
public String tracksAssociatename()
{
return associateName;
}
public int getWorkStatus()
{
System.out.println("Enter the number of days");
days = sc.nextInt();
return days;
}
public void setWorkStatus(String workStatus)
{
this.workStatus=workStatus;
}
enter code here
public `enter code here`int tracksAssociateStatus()
{
return days;
}
public static void main(String args[])
{
Associate obj = new Associate();
obj.getAssociateName();
obj.getworkstatus();
System.out.println("The Associate name "+obj.tracksAssociatename()+" work Status "+obj.tracksAssociateStatus());
}
}
I have an enum with values VALID and INVALID, which have a boolean property associated with them. I would like to get the enum value based on a boolean value I provide.
If it is true I should get VALID, if it is false I should get INVALID. I would like to do so in a getter method like the below, based on the value of the member variable
public boolean getCardValidityStatus() {
return CardValidationStatus status = CardValidationStatus(this.mCardValidityStatus));
}
My code:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
private boolean isValid;
CardValidationStatus(boolean isValid) {
this.isValid = isValid;
}
public boolean getValidityStatus() {
return this.isValid;
}
}
You're able to achieve that using a static lookup method in the enum itself:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public static CardValidationStatus forBoolean(boolean status) {
//this is simplistic given that it's a boolean-based lookup
//but it can get complex, such as using a loop...
return status ? VALID : INVALID;
}
}
And the appropriate status can be retrieved using:
public CardValidationStatus getCardValidityStatus() {
return CardValidationStatus.forBoolean(this.mCardValidityStatus));
}
I would add a parse method to your enum, which takes the boolean, iterates over all the values and returns the one that matches, for example:
public CardValidationStatus parse(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
#ernest_k solution made this work, but I think that's not reliable solution.
You should always do code which is independent.
Because his solution is hardcoded. What if values of VALID & INVALID are changed. Will you change your forBoolean logics also?
Because he did not check what the Enum fields are holding inside it.
Reliable solution will be #DaveyDaveDave answer. This will also work when you have many status with VALID & INVAlID.
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public CardValidationStatus forBoolean(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
}
Suggestion (Easiest way I think)
Why are you making Enum just for storing 2 boolean values?
Just make static boolean named by VALID & INVALID.
public static final boolean CARD_STATUS_VALID = true;
public static final boolean CARD_STATUS_INVALID = false;
if(cardStatus == CARD_STATUS_VALID){
// todo
}
I have a class, LazyAuthor, that stores information about an author and can have a 'rival' (another object of the same class) set for it, and various methods cause them to interact with each other. The LazyAuthor class also relies on another class Book which stores details of the book's title, etc.
I am trying to set up a method rivalsLastTitle that returns the title (from the corresponding Book object) for the rival's last book. I have written this as:
public String rivalsLastTitle(){
return currentRival.getLastBook().getTitle();
}
where the corresponding methods I've called are
public Book getLastBook(){
return lastBook;
}
from the LazyAuthor class and
public String getTitle(){
return title;
}
from the Book class. currentRival is an object of the LazyAuthor class.
However this is returning a null value so clearly my syntax is wrong. I'm not sure how to write this code in order for it to return the title of the rival's lastBook object. I believe I may be overcomplicating the instruction for the return statement but I have seen multiple method calls like this work before.
Any help would be appreciated, I would be happy to share other parts of the code if that's useful. Thank you
edit: Here is the code for the whole LazyAuthor class. Apologies for length:
// fields (data members) go here
private int currentMoney, newMoney;
private String authorName, name;
private Book lastBook, bestBook, rLastBook, newBook, newLastBook,newBestBook, nextBook;
private LazyAuthor currentRival, newRival;
private boolean happy, jealous, lol;
// methods go here
public LazyAuthor(String name){
authorName = name;
currentMoney = 10000;
}
//set methods
public void setLastBook(Book newLastBook){
lastBook = newLastBook;
}
public void setBestBook(Book newBestBook){
bestBook = newBestBook;
}
public void setRival(LazyAuthor newRival){
newRival = currentRival;
}
public void setMoney(int newMoney){
newMoney = currentMoney;
}
public void setName(String name){
name = authorName;
}
//get methods
public Book getLastBook(){
return lastBook;
}
public Book getBestBook(){
return bestBook;
}
public int getMoney(){
return currentMoney;
}
public String getName(){
return authorName;
}
public LazyAuthor getRival(){
return currentRival;
}
// complex methods
public String lastTitle(){
return lastBook.getTitle();
}
public String bestTitle(){
return bestBook.getTitle();
}
public String rivalsLastTitle(){
rLastBook = currentRival.getLastBook();
return rLastBook.getTitle();
}
public boolean isHappy(){
// happy if last book written is their best OR they sold film rights for it
if(lastBook == bestBook || lastBook.filmRightsAreSold() == true) {
happy = true; }
else {
happy = false; }
return happy;
}
public boolean isJealous(){
// jealous if their rival's last book made more money, but isn't jealous if they managed to sell film rights for their last book
rLastBook = currentRival.getLastBook();
if(rLastBook.getValue() > lastBook.getValue() ){
jealous = true; }
else {
jealous = false;}
if(lastBook == bestBook || lastBook.filmRightsAreSold() == true) {
jealous = false; }
return jealous;
}
public boolean laughsAboutRival(){
// they laugh if their rival didn't sell film rights for their last book or if it made less than their own
rLastBook = currentRival.getLastBook();
if(rLastBook.filmRightsAreSold() == false || currentRival.getLastBook().getValue() < lastBook.getValue()) {
lol = true; }
else {
lol = false;}
return lol;
}
public void buyBackRightsOfLastBook(){
if(lastBook.filmRightsAreSold() == true && currentMoney >= lastBook.getBuyBackCost() ){
setMoney(currentMoney - lastBook.getValue() );
lastBook.buyBackRights(); }
}
public void writeNewBook(Book newBook){
// writes new book only if their last book wasn't their best, and they didn't sell the rights to it.
if(lastBook!=bestBook && lastBook.filmRightsAreSold() == false && currentMoney < lastBook.getValue() ){
lastBook = newBook;
currentMoney= currentMoney + lastBook.getValue();
}
}
edit 2: having just looked over the code again while editing this post, I seem to have assigned the labels in some of the set methods the wrong way around. I'm editing this now and will see if this fixes the null pointers.
edit 3: this seems to have worked, thank you all for the reassurance that my original syntax was correct and also for clarification on what a null value implies has gone wrong :)
On my course I am learning the different development patterns and the problem i am stuck with is an implementation of the Observer Pattern [1]: http://www.oodesign.com/observer-pattern.html, and them problem i am having is passing a value from the subject, that has been set using a JUnit test, to the observer to it can buy/sell a number of shares. My main question is: What's the problem i am not seeing? and a secondary question: Would my buying/selling of shares code work? if doesn't work, please don't post a solution to the 2nd as i would like to fix atleast one bit myself.
Interface:
public interface ShareWatcher {
public void updatePrice(double price);}
Subject:
public class Share{
public double price = 1.00;
ArrayList<ShareWatcher> list = new ArrayList<ShareWatcher>();
public double getPrice() {
return price;
}
public boolean addShareWatcher(StockBroker stockBroker) {
boolean result;
if(!list.contains(stockBroker)){
list.add(stockBroker);
result = true;
}else{
result = false;
}
return result;
}
public boolean removeShareWatcher(StockBroker stockBroker) {
boolean result;
if(list.contains(stockBroker)){
list.remove(stockBroker);
result = true;
}else{
result = false;
}
return result;
}
}
Observer:
public class StockBroker implements ShareWatcher{
Share share = new Share();
public int portfolio ;
double price;
double buy, sell;
public int increment;
public StockBroker(double SB_BUY, double SB_SELL, int SB_INCREMENT) {
this.buy = SB_BUY;
this.sell = SB_SELL;
this.increment = SB_INCREMENT;
System.out.println(buy + "" + sell + "" + increment);
}
#Override
public void updatePrice(double price) {
this.price = share.getPrice();
}
public int getPortfolio() {
while (price > 2 && price < 2){
if(price < buy){
portfolio = portfolio + increment;
System.out.println("SB2 " + portfolio);
}else if(price > sell){
portfolio = portfolio - increment;
}
}
return portfolio;
}
}
and not sure if this would be needed on here, if not feel free to edit out, but the JUnit Test:
public void testChangePrice1() {
final Share share = new Share();
final StockBroker stockBroker = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
assertTrue(share.addShareWatcher(stockBroker));
share.setPrice(PRICE5);
final int expectedValue2 = 500;
assertEquals(expectedValue2, stockBroker.getPortfolio());
}
To me it seems that you are not understanding that the observer pattern is basically about a CALLBACK after a certain event.
Meaning: the observers can register themselves somewhere; in your terms, they would be using the addShareWatcher() method of Subject.
Then, when for some reason the price is changed, Subject should iterate its list of ShareWatchers ... and invoke "updatePrice()" on each of the objects.
Side note: of course this is just example code; but keep in mind that you should not use ordinary "double" values that represent currency (see http://www.javapractices.com/topic/TopicAction.do?Id=13 on alternatives).
I have class that stores groups' permissions for single element. In it, I've also class for single group's permissions set. The solution is simple, looks that.
But I have no idea how can I get single permissions set using value in it (in group_id). How can I do that?
public class PermissionsData {
private List<PermissionsDataSingle> permissionsData;
PermissionsData(List<PermissionsDataSingle> permissionsData) {
this.permissionsData = permissionsData;
}
public PermissionsDataSingle getPermissionsByGroupID(int group_id) {
// ToDo
}
public class PermissionsDataSingle {
public int group_id;
public boolean canView;
public boolean canRead;
public boolean canReply;
public boolean canStart;
public boolean canUpload;
public boolean canDownload;
PermissionsDataSingle(int group_id, boolean canView, boolean canRead, boolean canReply, boolean canStart, boolean canUpload, boolean canDownload) {
this.group_id = group_id;
this.canView = canView;
this.canRead = canRead;
this.canReply = canReply;
this.canStart = canStart;
this.canUpload = canUpload;
this.canDownload = canDownload;
}
}
}
If the list is always very short, you can simply iterate through it and check the group_id for each entry. Otherwise it's better to use a map.
for (PermissionsDataSingle pds : permissionsData) {
if (pds.group_id == group_id) {
return pds;
}
}
// Not found