To every user you create, you’re saying that the id of it one is 1. That’s because the command int id = 1 is within the class User, and the method gerarid(), which is also within the class, will only increase the id of User which method gerarid() belongs, for example:
User u1 = new User(); // u1 possui um atributo chamado id (u1.id) com o valor 1
User u2 = new User(); // u2 possui um atributo chamado id (u2.id) com o valor 1
u1.gerarid();
By calling u1.gerarid(), the instruction id++ is increasing the id of User u1, unrelated to u2, much less with your id (u2.id). The result of the above code would be:
u1.id: 2 // O id de u1 foi incrementado ao chamar u1.gerarid()
u2.id: 1 // Não foi alterado
To solve your problem, you need a variable that does not belong to a User, this variable will save the id that the next User to be created must have:
public class User {
// ...
int id; // Receberá o valor de contadorDeId
// ...
}
public class Mein {
public static void main(String[] args) {
int contadorDeId = 1;
User u1 = new User();
u1.id = contadorDeId++; // Atribui e depois incrementa contadorDeId para 2
// ...
User u2 = new User();
u2.id = contadorDeId++; // Atribui e depois incrementa contadorDeId para 3...
}
}
With this, you don’t need the method gerarId(), at least not within the class User. You can use the concept of builders to assign the id every new User in a more elegant way.
You need to capture the generated ID number, or the highest number and add
1from it. What happens in your code is that each time the script is executed you put the id as1.– Erico Calasans