java编写读者类实现增删改查和充值,编号流水自动增长的代码
时间: 2023-12-03 20:46:49 浏览: 45
下面是一个简单的Java读者类,包含增删改查和充值功能,同时实现了编号流水自动增长的功能:
```
public class Reader {
private static int nextId = 1;
private int id;
private String name;
private double balance;
public Reader(String name) {
this.id = nextId++;
this.name = name;
this.balance = 0.0;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
public boolean withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
return true;
} else {
return false;
}
}
public static void resetNextId() {
nextId = 1;
}
public static void main(String[] args) {
Reader reader1 = new Reader("Alice");
Reader reader2 = new Reader("Bob");
System.out.println("Reader 1: " + reader1.getId() + " " + reader1.getName() + " " + reader1.getBalance());
System.out.println("Reader 2: " + reader2.getId() + " " + reader2.getName() + " " + reader2.getBalance());
reader1.deposit(100.0);
reader2.deposit(50.0);
System.out.println("Reader 1 balance after deposit: " + reader1.getBalance());
System.out.println("Reader 2 balance after deposit: " + reader2.getBalance());
boolean success = reader1.withdraw(50.0);
if (success) {
System.out.println("Reader 1 balance after withdrawal: " + reader1.getBalance());
} else {
System.out.println("Reader 1 withdrawal failed: insufficient balance");
}
success = reader2.withdraw(100.0);
if (success) {
System.out.println("Reader 2 balance after withdrawal: " + reader2.getBalance());
} else {
System.out.println("Reader 2 withdrawal failed: insufficient balance");
}
}
}
```
在这个代码中,我们使用了静态变量`nextId`来实现编号流水自动增长的功能。在每次创建新的读者对象时,其编号都会自动增长。同时,我们实现了`deposit`和`withdraw`方法来充值和提现读者的账户余额,以及`resetNextId`方法来重置下一个读者对象的编号。在主函数中,我们创建了两个读者对象,并进行了充值、提现等操作,以测试类的功能是否正常。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)