这是一个更大的项目的片段。该项目旨在成为客户的客户经理+汇款的工作经理。在继续之前,我有一个我不明白的“小”问题。我想知道为什么
System.out.println(myJobOrganizer.jobNumber); // in the Main.java
输出0,尽管我已将两个作业添加到jobList。打印jobList本身时,它会打印出来
[[[customer1;adress1;accountBalance1];[customer2;adress2;accountBalance2];moneyToTransfer];[[customer3;adress3;accountBalance3];[customer4;address4;accountBalance4];moneyToTransfer2]]
jobOrganizer.java
import java.util.ArrayList;
import java.util.List;
public class jobOrganizer {
private static final jobOrganizer myJobOrganizer = new jobOrganizer();
public static jobOrganizer getMyJobOrganizer() {
return myJobOrganizer;
}
private List<job> jobList = new ArrayList<job>();
public int jobNumber = jobList.size();
public void add_job(job newJob) {
this.jobList.add(newJob);
}
public Iterable<job> all_jobs() {
return this.jobList;
}
public static jobOrganizer getInstance() {
return myJobOrganizer;
}
}
job.java
public class job implements Runnable {
private customer kunde1;
private customer kunde2;
private Double transfer;
public job(customer kunde1, customer kunde2, Double transfer) {
this.kunde1 = kunde1;
this.kunde2 = kunde2;
this.transfer = transfer;
}
@Override
public String toString() {
return "[" + kunde1 + "; " + kunde2 + "; " + transfer + "]";
}
public void run() {
System.out.println("Starting transfer");
Double geber = this.kunde1.getAccountBalance();
Double nehmer = this.kunde2.getAccountBalance();
Double geberNeu = geber - this.transfer;
this.kunde1.setAccountBalance(geberNeu);
Double nehmerNeu = nehmer + this.transfer;
this.kunde2.setAccountBalance(nehmerNeu);
System.out.println("Transfer done");
}
}
Main.java
public class Main {
public static void main(String[] args) {
customerOrganizer myCustomerOrganizer = new customerOrganizer();
jobOrganizer myJobOrganizer = new jobOrganizer();
customer mueller = new customer("Tim Mueller", "Strasse 1", 1077.00);
customer john = new customer("John Doe", "Strasse 2", 503.00);
customer meier = new customer("John Meier", "Strasse 3", 8500.50);
customer wurst = new customer("Hans Wurst", "Strasse 4", 1000.00);
myCustomerOrganizer.add_customer(mueller);
myCustomerOrganizer.add_customer(john);
myCustomerOrganizer.add_customer(meier);
myCustomerOrganizer.add_customer(wurst);
job transfer1 = new job(meier, wurst, 500.50);
job transfer2 = new job(mueller, john, 77.00);
myJobOrganizer.add_job(transfer1);
myJobOrganizer.add_job(transfer2);
System.out.println(myJobOrganizer.jobNumber);
System.out.println(myJobOrganizer.all_jobs().toString());
}
}
最佳答案
public int jobNumber = jobList.size();
不会被更新,所以要这样做,这将返回当前的jobList,而不像您的字段那样存储它的实例。
public int jobNumber(){
return jobList.size();
}