I want to create objects with a name and a unique ID number that increments with the creation of each user.
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.
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:
class User {
private static int uid = 0;
private String name;
private int id;
public User(String name) {
this.id = uid++;
this.name = name;
}
// getters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.