1

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

ID - 姓名 - 年龄

1 - 保罗 - 60

2 - 里吉斯 - 25

3 - 安娜 - 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;
}
4

2 回答 2

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;
    }
}
于 2012-09-29T21:58:57.907 回答
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);
    }
于 2012-09-29T21:55:39.053 回答