第九章第二题(Stock类)(Stoke class)

(60) 2024-04-12 21:01:01

第九章第二题(Stock类)(Stoke class)

  • 9.2(Stock类)遵照9.2节中Circle类的例子,设计一个名为Stoke的类。这个类包括:

    • 一个名为symbol的字符串数据域表示股票代码。
    • 一个名为name的字符串数据域表示股票名字。
    • 一个名为previousClosingPrice的double类型数据域,他存储的是前一日的股票值。
    • 一个名为currentPrice的double类型数据域,他存储的是当时的股票值。
    • 一个创建一只只有特定代码和名字的股票的构造方法。
    • 一个名为getChangePercent()的方法,发挥从previousClosingPrice到currentPrice变化的百分比。

    画出该类的UML图并实现这个类。编写一个测试程序,创建一个Stoke对象,他的股票代码是ORCL,股票的名字为Oracle Corporation,前一日收盘价是34.5。设置新的当前值为34.35,然后显示市值变化的百分比。
    9.2(Stoke class)Follow the example of the circle class in Section 9.2 to design a class called stoke. This class includes:

    • A string data field named symbol represents the stock code.
    • A string data field named name represents the stock name.
    • A double type data field called previous closing price stores the stock value of the previous day.
    • A double type data field called currentprice stores the current stock value.
    • A constructor that creates a stock with a specific code and name.
    • A method called getchangepercent() plays the percentage of change from previous closing price to current price.

    Draw the UML diagram of the class and implement the class. Write a test program, create a stoke object, his stock code is orcl, the name of the stock is Oracle Corporation, the previous day’s closing price was 34.5. Set the new current value to 34.35, and then display the percentage of market value change.

  • 参考代码:

package chapter09;

public class Code_02 { 
   
    public static void main(String[] args) { 
   
        Stock stock = new Stock("ORCL","Oracle Corporation");
        System.out.println("The change percent is: " + stock.getChangePercent(34.5,34.35));
    }
}
class Stock{ 
   
    private String symbol;
    private String name;
    private double preciousClosingPrice;
    private double currentPrice;
    Stock(String newSymbol,String newName){ 
   
        this.name = newName;
        this.symbol = newSymbol;
    }
    public String getChangePercent(double preciousClosingPrice,double currentPrice){ 
   
        return (currentPrice - preciousClosingPrice) / (preciousClosingPrice * 100) + "%";
    }
}

  • 结果显示:
The change percent is: -4.347826086956481E-5%

Process finished with exit code 0

THE END

发表回复