自动生成ID

时间:2013-04-07 18:19:08

标签: java

我正在尝试为客户自动生成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");
}

2 个答案:

答案 0 :(得分:3)

您永远不会设置ID,这就是为零的原因。

您可以使用private 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
}

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

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

答案 1 :(得分:1)

customerID = idCounter++;移至构造函数。