how to develop a class named stock tracker that takes the definitions: The const
ID: 3678121 • Letter: H
Question
how to develop a class named stock tracker that takes the definitions:
The constructor "StockTracker ()" creates an initially empty StockTracker object
buy(quanity, price) method performs a purchase transaction. Quantity should be a positive integer and price should be a positive floating point value. A ValueError will be raised if any of these conditions is not satisfied
sell(quanity,price) method performs a sell transaction. Quantity should be a positive integer and price should be a positive floating point value. Also the quantity to sell must be equal to or less than the total number of shares on hand. A ValueError will be raised if any of these conditions is not satisfied. It returns the gain (or loss) for this particular transaction.
getProfit () method returns the total gain (or loss) since the creation of the object
getQuantityOnHand () method the quantity of shares on hand
Explanation / Answer
Code:
public class StockTracker
{
int no_of_share; // total no of quantity
float total_profit; // total profit
float current_price; // current price
StockTracker()// initialization of all variable
{
no_of_share = 0;
total_profit = 0;
current_price = 0;
}
void buy(float quantity, float price)
{
if (quantity <= 0 || (quantity - (int) quantity) != 0 || price <= 0)// checked for given condition
{
System.out.println("Value Error");
return;
}
no_of_share += quantity;
current_price = price;
}
float sell(float quantity, float price)
{
if (quantity <= 0 || (quantity - (int) quantity) != 0 || price <= 0)// checked for given condition
{
System.out.println("Value Error");
return (float) 0.0;
}
if (quantity > no_of_share)
{
System.out.println("Value Error");
return (float) 0.0;
}
float prof = quantity * price - current_price * quantity;// calculating profit value
total_profit += prof;
return prof; // in case of loss profit will be negative
}
int getQuantityOnHand()
{
return no_of_share;
}
float getProfit()
{
return total_profit;// it will return negative if stock tracker is in loss
}
}
If you have any doubt then please comment below
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.