2

我正在尝试为客户自动生成一个 id,每次我得到的都是 0。

很确定问题出在public void regCustomer().

public class User {
private String firstName, gender, age;
String surename;
private int customerID;
private static int idCounter = 1000;
User next;

public User(String fN, String sn, String g, String a) {
    firstName = fN;
    surename = sn;
    gender = g;
    age = a;
    //customerID = cID;
    next = null;
}

public void setCustomerID() {
    customerID = idCounter++;
}

public int getCustomerID() {
    return customerID;
}

public String toString() {
    return customerID + "\t" + surename + "\t" + firstName + "\t" + age
            + "\t" + gender;

}

}

Window课堂上

public void regCustomer() {


    //int customerID = 0;//= Integer.parseInt(customerIDField.getText());
    String firstName = firstNameField.getText();
    String surename = surenameField.getText();
    String gender = genderField.getText();
    String age = ageField.getText();

    if (!firstName.equals("") && !surename.equals("") && !gender.equals("")&& !age.equals("")) {
        userA.regCustomer(new User(firstName, surename, gender,age));
        User u = new User(firstName, surename, gender,age);
        u.getCustomerID();
        customerIDField.setText("");
        firstNameField.setText("");
        surenameField.setText("");
        ageField.setText("");
        genderField.setText("");
        firstNameField.requestFocus();
    } else
        JOptionPane.showMessageDialog(this, "Alle felt må fylles inn");
}
4

2 回答 2

4

您从不设置 ID,这就是它为零的原因。

您可以使用 aprivate static final AtomicInteger来生成您的 id 序列;只需在构造函数中读取它:

private static AtomicInteger ID_GENERATOR = new AtomicInteger(1000);

public User(String fN, String sn, String g, String a) {
    customerID = ID_GENERATOR.getAndIncrement();
    //rest of constructor
}

您应该使用 anAtmoicInteger因为这是线程安全的并且该getAndIncrement方法是原子的。没有这样的保证int

需要回答的问题是这些项目是否以任何方式持久化,如果是,那么会发生什么 - 使用此技术生成 id 将始终从 1000 开始。

于 2013-04-07T18:25:12.097 回答
1

移动customerID = idCounter++;到构造函数。

于 2013-04-07T18:24:56.360 回答