i try to add some objects(servei) in this code and the new one allways overwrite the last one and i can't find the error :/,i have two points p and i,I use i for the array only when deleting llista[p] objects,cause i don't want null values inside my array,i added the code,when i use e,and servei cause some people said that there could be the error too.
System.out.println(llista.afegirServei(serv)); // that's what i use to add a new servei
public class Llistaservei {
private int i;
private Servei[] llista;
private int p = 0;
private float opinio;
public Llistaservei(int Max_Serv) {
llista = new Servei[Max_Serv];
}
public String AfegirServei(Servei servei) {
if (ValidServei(servei.getNom()) == i) {
return ("El servei ja existeix"); //if exist return that "servei" exist.
} else { ***//finally works cleaning eclipse cache...***
llista[p]=servei;
p++;
return ("El servei s'ha creat correctament");// I add a new "Servei to the array" if doesn't exist
}
}
public String EliminarServei(String nom){
if(ValidServei(nom)==-1){
llista[i]=llista[p]; //here i use 2 pointers p,i cause i don't want null
llista[p]=null; //in the middle of the array
p--;
return ("El servei s'ha eliminat correctament"); //if is valid
} //return "servei" deleted
public int ValidServei(String nom) {
for (i = 0; ((i < p) && (i < llista.length)); i++) {
if (nom.equalsIgnoreCase(llista[i].getNom())) {
return i;
}
}
}
}
Since
ValidServei
returnsi
and sharesi
your method will always return a value wherei
matches it here -Instead you could write a
contains
like,And Java method names start with a lower case letter by convention. Like,
Finally, you should probably be using a
Set<Servei>
collection (instead of an array) like,