[英]Create unique ID with constructor
I want to create objects with a name and a unique ID number that increments with the creation of each user.我想创建具有名称和唯一 ID 号的对象,该 ID 号随着每个用户的创建而增加。
class user {
static int uid = 0;
String name;
public user (String name){
User.uid = uid++;
this.name = name;
}
}
When creating user objects in a main method and printing out their ID they all return 0. I think there is a simply fix to this but can't seem to find it elsewhere online.在 main 方法中创建用户对象并打印出他们的 ID 时,它们都返回 0。我认为有一个简单的解决方法,但似乎无法在网上的其他地方找到它。
Your code has several problems:您的代码有几个问题:
The code should be代码应该是
class User {
private static int uid = 0;
private String name;
private int id;
public User(String name) {
uid++;
this.id = uid;
this.name = name;
}
// getters
}
or, if you want the IDs to start at 0:或者,如果您希望 ID 从 0 开始:
class User {
private static int uid = 0;
private String name;
private int id;
public User(String name) {
this.id = uid++;
this.name = name;
}
// getters
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.