Assignment7_2.java - design a class named Stock that contains: A string data fie
ID: 675257 • Letter: A
Question
Assignment7_2.java - design a class named Stock that contains:
A string data field named symbol for the stock's symbol.
A string data field named name for the stock's name.
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 specified symbol and name.
A method named getChangePercent() that returns the percentage change from previousClosingPrice to currentPrice.
Implement the class. Write a test program that creates a Stock object with the stock symbol JAVA, the name Sun Microsystems Inc. and the previous closing price of 4.5. Set a new current price to 4.35 and display the price-change percentage.
Explanation / Answer
import java.util.Scanner;
public class StockTest {
public static void main(String[] args) throws Exception{
Stock st = new Stock("JAVA", "Sun Microsystems");
st.setPreviousClosingPrice(4.5);
st.setCurrentPrice(4.35);
double pchange = st.getChangePercent();
System.out.println("Symbol: "+st.getSymbol()+" Name: "+st.getName());
System.out.println("previous closing price : "+st.getPreviousClosingPrice()
+" current price: "+ st.getCurrentPrice()
+" change (%) : "+pchange);
}
}
class Stock {
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;
public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
previousClosingPrice = 0;
currentPrice = 0;
}
public double getChangePercent() {
double changePercent = 0;
if(previousClosingPrice != 0) {
double change = (currentPrice-previousClosingPrice) ;
changePercent = (change * 100)/ previousClosingPrice;
}
return changePercent;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPreviousClosingPrice() {
return previousClosingPrice;
}
public void setPreviousClosingPrice(double previousClosingPrice) {
this.previousClosingPrice = previousClosingPrice;
}
public double getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(double currentPrice) {
this.currentPrice = currentPrice;
}
}
--------------output-----------------
Symbol: JAVA Name: Sun Microsystems
previous closing price : 4.5 current price: 4.35 change (%) : -3.333333333333341
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.