Hi I need help creating a program in JAVA Applications. (The Stock class) Design
ID: 3914572 • Letter: H
Question
Hi I need help creating a program in JAVA Applications.
(The Stock class) Design a class named Stock that contains:
A string data field named symbol for the stock's symbol
A string data field named name fo rthe stock's symbol
A double data field named previousClosingPrice that stores the stock price for the previous day.
A double data field named currentPrice that stores the stock price for the current time
A constructor that creates a stock with the specified symbol and name
A method named getChangePercent() that returns the percentage changed from previousClosingPrice to currentPrice
Create a test program that creates a Stock object with the stock symbol ORCL, the name Oracle Corporation, and the previous closing price of 34.5. Set a new current price to 34.35 and display the price-change percentage.
Explanation / Answer
Stock.java
public class Stock
{
private String symbol,name;
private double previousClosingPrice, currentPrice;
public Stock()
{
symbol = " ";
name = " ";
previousClosingPrice = 0;
currentPrice = 0;
}
public Stock(String symbol, String name)
{
this.symbol = symbol;
this.name = name;
}
public String getSymbol()
{
return symbol;
}
public String getName()
{
return name;
}
public void setSymbol(String symbol1)
{
symbol = symbol1;
}
public void setName(String name1)
{
name = name1;
}
public double getPreviousClosingPrice()
{
return previousClosingPrice;
}
public double getChangePercent() {
return (Math.abs(previousClosingPrice-currentPrice)*100)/previousClosingPrice;
}
public double getCurrentPrice()
{
return currentPrice;
}
public void setPreviousClosingPrice(double price)
{
previousClosingPrice = price;
}
public void setCurrentPrice(double price)
{
currentPrice = price;
}
public double changePercent()
{
return (currentPrice - previousClosingPrice) / previousClosingPrice;
}
}
StockTest.java
public class StockTest {
public static void main(String[] args) {
Stock s = new Stock("ORCL","Oracle Corporation");
s.setPreviousClosingPrice(34.5);
s.setCurrentPrice(34.35);
System.out.println("Price change percentage: "+s.getChangePercent());
}
}
Output:
Price change percentage: 0.43478260869564805