使用熟悉的编程语言(如Java、Python等),编写一个类(或函数),用于处理收支记录的录入和余额计算。
时间: 2024-09-18 16:03:02 浏览: 28
在Java中,我们可以创建一个名为`FinancialTransaction`的类来处理收支记录。这个类可以包含两个私有变量:`income`和`expense`,分别表示收入和支出,还有一个公共属性`balance`来存储当前余额。我们还需要提供构造函数初始化余额,以及添加收入和支出的方法。
```java
public class FinancialTransaction {
private double income;
private double expense;
private double balance;
// 构造函数
public FinancialTransaction() {
this.balance = 0;
}
// 添加收入方法
public void addIncome(double amount) {
this.income += amount;
updateBalance();
}
// 添加支出方法
public void addExpense(double amount) {
this.expense += amount;
updateBalance();
}
// 更新余额方法
private void updateBalance() {
this.balance = this.income - this.expense;
}
// 获取余额方法
public double getBalance() {
return this.balance;
}
}
// 示例:
FinancialTransaction transaction = new FinancialTransaction();
transaction.addIncome(500);
transaction.addExpense(200);
System.out.println("Current Balance: " + transaction.getBalance());
```
在Python中,你可以使用类定义类似的方式:
```python
class Transaction:
def __init__(self):
self.income = 0
self.expense = 0
self.balance = 0
def add_income(self, amount):
self.income += amount
self.update_balance()
def add_expense(self, amount):
self.expense += amount
self.update_balance()
def update_balance(self):
self.balance = self.income - self.expense
def get_balance(self):
return self.balance
# 示例:
trans = Transaction()
trans.add_income(500)
trans.add_expense(200)
print("Current Balance:", trans.get_balance())
```
阅读全文