java股票类包括代码名称前一日收款价当前价,涨跌幅度,涨跌价格。方法获取当前价格,计算涨幅
时间: 2024-10-10 15:14:17 浏览: 27
在Java中,你可以创建一个名为`Stock`的类来表示股票的基本信息,如代码名称、昨日收盘价、当前价格、涨跌幅度和涨跌金额。这里是一个简单的例子:
```java
public class Stock {
private String codeName;
private double yesterdayClosingPrice;
private double currentPrice;
private double changeRate;
private double changeAmount;
// 构造函数
public Stock(String codeName, double yesterdayClosingPrice, double currentPrice) {
this.codeName = codeName;
this.yesterdayClosingPrice = yesterdayClosingPrice;
this.currentPrice = currentPrice;
calculateChange();
}
// 获取当前价格的方法
public double getCurrentPrice() {
return currentPrice;
}
// 计算涨幅和涨跌金额的方法
private void calculateChange() {
if (yesterdayClosingPrice > 0) {
changeRate = (currentPrice - yesterdayClosingPrice) / yesterdayClosingPrice * 100;
changeAmount = currentPrice - yesterdayClosingPrice;
} else {
throw new IllegalStateException("Cannot calculate change with a zero or negative previous price");
}
}
// 如果需要提供获取涨跌幅和涨跌金额的方法
public double getChangeRate() {
return changeRate;
}
public double getChangeAmount() {
return changeAmount;
}
// 示例如何使用
public static void main(String[] args) {
Stock stock = new Stock("AAPL", 145.20, 150.50);
System.out.println("Code Name: " + stock.getCodeName());
System.out.println("Current Price: " + stock.getCurrentPrice());
System.out.println("Change Rate: " + stock.getChangeRate() + "%");
System.out.println("Change Amount: $" + stock.getChangeAmount());
}
}
```
阅读全文