Java:如何使用ArrayList在寄存器中使用计数器

时间:2012-09-29 21:54:03

标签: java arraylist

我希望每个新名称的ID为1,2,3,4,即

ID - 姓名 - 年龄

1 - 保罗 - 60

2 - Regis - 25

3 - Ana - 20

自动识别

static void register(ArrayList mylist) {
        int i = 1;
        Scanner in = new Scanner(System.in);
        Peoples p = new Peoples();
//        System.out.print("ID: ");
//        p.ID = in.nextInt();
        p.ID = i;
        i++;
        in.nextLine();
        System.out.print("Name: ");
        p.name = in.nextLine();
        System.out.print("Age: ");
        p.age = in.nextInt();
        mylist.add(p);
    }


public class Peoples {
    public int ID;
    public String name;
    public int age;
}

2 个答案:

答案 0 :(得分:3)

我会稍微修改一下Peoples类(顺便说一下,对类名使用单数形式是个好习惯。)

public class Person {
    private static int lastId;
    private int id;
    private String name;
    private int age;

    public Person() {
      id = Person.lastId++;
    }

    public void setName(String name) {
      this.name = name;
    }

    public void setAge(int age) {
      this.age = age;
    }
}

答案 1 :(得分:2)

您需要在方法之外声明变量i = 1。因为您不希望它在每次方法调用时都被初始化为相同的值..

static int i = 1;
static void register(ArrayList mylist) {

        Scanner in = new Scanner(System.in);
        Peoples p = new Peoples();
        p.ID = i++;   // You can do increment + assignment on the same line.
     // i++;  // No need to increment in separate line
        in.nextLine();
        System.out.print("Name: ");
        p.name = in.nextLine();
        System.out.print("Age: ");
        p.age = in.nextInt();
        mylist.add(p);
    }