public void removeElement( String candidate ) {
// hitta elementet som ska tas bort och placera det sist i arrayen
for( int i = 0; i < carRegister.length; i ) {
String s = carRegister[i];
if( s.equals( candidate ) ) {
// byt plats med sista elementet
String temp = carRegister[carRegister.length-1];
carRegister[carRegister.length-1] = s;
carRegister[i] = temp;
}
}
// Ta bort elementet genom att kopiera över alla utom sista elementet till en ny array
String[] tempArray = new String[carRegister.length-1];
for( int i = 0 ; i < carRegister.length-1; i ) {
tempArray[i] = carRegister[i];
}
// den nya arrayen tilldelas arrayen carRegister
carRegister = tempArray;
}
My problem with the code is that I do not find a way to prevent the copying from the second for loop if the user input (candidate) does not match any of the elements in the array. As you can see it removes Mazda even though the input is "Tesla". I don't know how to stop it from removing the last element in the array in this case.
CodePudding user response:
Why not create a variable to store whether you have found the candidate or not? Then, if the variable says that you have not found it, the second loop can be avoided. For example,
...
boolean foundCandidate = false; // initialized to "did not find it"
for( int i = 0; i < carRegister.length; i ) {
String s = carRegister[i];
if( s.equals( candidate ) ) {
// changed if found
foundCandidate = true;
...
// now, you can avoid this loop (and modifying carRegister) if it is not necessary
if( foundCanidate) {
...
}