我在我的程序中遇到了构造函数的小问题。它是一个简单的银行数据库,用于存储客户数据。我必须实现在两个账户之间存入、提取和转移现金的方法。我已经实现了这种构造函数来添加新的银行账户:
public Customer() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter id of customer:");
this.id = scan.nextLine();
File folder = new File("CustomerDataBase" + File.separator + this.id + ".txt");
if(folder.exists()) {
System.out.println("Customer ID already exists!");
System.exit(1);
}
try {
System.out.println("Enter name of customer:");
this.name = scan.nextLine();
System.out.println("Enter surname of customer:");
this.surname = scan.nextLine();
System.out.println("Enter PESEL number of customer:");
this.pesel = scan.nextLine();
System.out.println("Enter address of customer:");
System.out.println(" Street:");
this.adressStreet = scan.nextLine();
System.out.println(" City:");
this.adressCity = scan.nextLine();
System.out.println(" Zip Code: ");
this.zipCode = scan.nextLine();
System.out.println("Enter funds of Customer:");
this.funds = Double.parseDouble(scan.nextLine());
this.saveCustomer();
scan.close();
}catch(NumberFormatException e) {
System.out.println("Error : " + e);
System.exit(1);
}
}
然后我有一个方法withdraw
:
static void withdraw (int amount, int id) {
File f = new File("CustomerDataBase" + File.separator + String.valueOf(id) + ".txt");
Scanner fRead;
Customer tempCustomer = new Customer();
try{
fRead = new Scanner(f);
tempCustomer.id = fRead.nextLine();
tempCustomer.name = fRead.nextLine();
tempCustomer.surname = fRead.nextLine();
tempCustomer.pesel = fRead.nextLine();
tempCustomer.adressStreet = fRead.nextLine();
tempCustomer.adressCity = fRead.nextLine();
tempCustomer.zipCode = fRead.nextLine();
tempCustomer.funds = Double.parseDouble(fRead.nextLine()) - id;
fRead.close();
tempCustomer.saveCustomer();
}catch(FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
}
}
该withdraw
方法从文件中读取数据并且必须将其存储在类中。所以我将对象创建为客户类型。但是我只想使用 Java 提供的“普通”(默认)构造函数,当您不声明自己的构造函数时。怎么做?我阅读了关于super():
声明,但如果我理解正确,它仅在您从另一个类继承时才有效。