I made a function to delete a specific element in the array, but the problem that am struggling with is that when we getting the value of the element that we want to remove from s.next() it's not removing but when we already initialized a value for it it is removing
for example, we have a function remove
public static String[] remove(String[] element, String value) {
int validSize = 0;
String[] n_elements = new String[0];
for (int i = 0; i < element.length; i ) {
if (element[i] == value) {
element[validSize] = element[i];
validSize ;
}
n_elements = new String[validSize];
if (validSize >= 0) System.arraycopy(element, 0, n_elements, 0, validSize);
}
return n_elements;
}
in main
public static void main(String[] args) {
String[] group_A = {"Alexandr", "Ahmed", "Maria", "elf", "Omar", "Mariam"};
Scanner s = new Scanner(System.in);
System.out.println(Arrays.toString(group_A));
String value = "elf";
//we already initialized a value for it
group_A = remove(group_A,value);
System.out.println(Arrays.toString(group_A));
}
}
output is correct
[Alexandr, Ahmed, Maria, elf, Omar, Mariam]
[Alexandr, Ahmed, Maria, Omar, Mariam]
but if we get value from the user in put it does not deleting
String value = s.next();
output is
[Alexandr, Ahmed, Maria, elf, Omar, Mariam]
elf
[Alexandr, Ahmed, Maria, elf, Omar, Mariam]
CodePudding user response:
Like @Oussama ZAGHDOUD said,
Instead of if (element[i] == value)
, Use if (element[i].equals(value))
.
CodePudding user response:
Your code miss a "!" before the condition and you need to use .equals() instead of"==":
public static String[] remove(String[] element, String value) {
int validSize = 0;
String[] n_elements = new String[0];
for (int i = 0; i < element.length; i ) {
if (! element[i] .equals( value )) {
element[validSize] = element[i];
validSize ;
}
n_elements = new String[validSize];
if (validSize >= 0) System.arraycopy(element, 0, n_elements, 0, validSize);
}
return n_elements;
}
public static void main(String[] args) throws IOException {
String[] group_A = {"Alexandr", "Ahmed", "Maria", "elf", "Omar", "Mariam"};
Scanner s = new Scanner(System.in);
System.out.println(Arrays.toString(group_A));
String value = s.nextLine();
//we already initialized a value for it
group_A = remove(group_A,value);
System.out.println(Arrays.toString(group_A));
}