java创建银行账户类SavingAccount,用静态成员变量存储年利率,用私有成员变量存储存款余额。提供计算年利息的方法和计算月利息(年利息/12)的方法。在主函数中建立SavingAccount的对象saver,从控制台输入存款额度和年利率,输出年利息和月利息。
时间: 2023-06-01 21:01:55 浏览: 263
以下是Java代码实现:
```
import java.util.Scanner;
public class SavingAccount {
private double balance; // 存款余额
private static double annualInterestRate; // 年利率
public SavingAccount(double balance) {
this.balance = balance;
}
// 设置年利率
public static void setAnnualInterestRate(double rate) {
annualInterestRate = rate;
}
// 计算年利息
public double calculateAnnualInterest() {
return balance * annualInterestRate;
}
// 计算月利息
public double calculateMonthlyInterest() {
return calculateAnnualInterest() / 12;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入存款额度:");
double balance = scanner.nextDouble();
System.out.print("请输入年利率:");
double annualInterestRate = scanner.nextDouble();
SavingAccount saver = new SavingAccount(balance);
SavingAccount.setAnnualInterestRate(annualInterestRate);
double annualInterest = saver.calculateAnnualInterest();
double monthlyInterest = saver.calculateMonthlyInterest();
System.out.println("年利息为:" + annualInterest);
System.out.println("月利息为:" + monthlyInterest);
}
}
```
运行结果:
```
请输入存款额度:10000
请输入年利率:0.05
年利息为:500.0
月利息为:41.666666666666664
```
阅读全文