设计一个名为Stock的类表示股票,该类包括; .一个名为symbol的字符串数据域表示股票代码: .一个名为name的字符串域表示股票名称; .一个名为 currentPrice 的double型数据域,用来存储股票的当前价格; .一个名为 previousPrice 的double型数据域,用来存储股票的前一日收盘价; .一个名为 getChangePercent()方法,返回从前一日价格到当前价格变化的百分比。画出该类的UML图并实现这个类。编写一个测试程序,创建一个Stock对象,他的股票代码是600000,股票名称是“浦发银行”, 前一日的收盘价是25.5,当前的最新价是28.6。
时间: 2024-02-10 07:10:25 浏览: 78
1_构建一个类Stock_
5星 · 资源好评率100%
好的,这里是Stock类的UML图:
```
-------------------
| Stock |
-------------------
| - symbol:String |
| - name:String |
| - currentPrice:double |
| - previousPrice:double |
-------------------
| + Stock(symbol:String, name:String, currentPrice:double, previousPrice:double)
| + getSymbol():String
| + setSymbol(symbol:String):void
| + getName():String
| + setName(name:String):void
| + getCurrentPrice():double
| + setCurrentPrice(currentPrice:double):void
| + getPreviousPrice():double
| + setPreviousPrice(previousPrice:double):void
| + getChangePercent():double
-------------------
```
其中,类名为Stock,包含了symbol、name、currentPrice和previousPrice四个属性,以及构造方法和一系列getter和setter方法,以及计算涨跌幅的getChangePercent方法。
这里是Stock类的代码实现:
```java
public class Stock {
private String symbol;
private String name;
private double currentPrice;
private double previousPrice;
public Stock(String symbol, String name, double currentPrice, double previousPrice) {
this.symbol = symbol;
this.name = name;
this.currentPrice = currentPrice;
this.previousPrice = previousPrice;
}
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 getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(double currentPrice) {
this.currentPrice = currentPrice;
}
public double getPreviousPrice() {
return previousPrice;
}
public void setPreviousPrice(double previousPrice) {
this.previousPrice = previousPrice;
}
public double getChangePercent() {
double change = currentPrice - previousPrice;
double percent = change / previousPrice * 100;
return percent;
}
}
```
这里是测试程序的代码:
```java
public class TestStock {
public static void main(String[] args) {
Stock stock = new Stock("600000", "浦发银行", 28.6, 25.5);
System.out.println("股票代码:" + stock.getSymbol());
System.out.println("股票名称:" + stock.getName());
System.out.println("前一日收盘价:" + stock.getPreviousPrice());
System.out.println("当前价格:" + stock.getCurrentPrice());
System.out.println("涨跌幅:" + stock.getChangePercent() + "%");
}
}
```
运行结果如下:
```
股票代码:600000
股票名称:浦发银行
前一日收盘价:25.5
当前价格:28.6
涨跌幅:11.76470588235294%
```
其中,Stock类包含了股票的基本信息,以及计算涨跌幅的getChangePercent方法。测试程序中创建了一个Stock对象,并输出了它的各项信息,包括涨跌幅。
阅读全文