I am making a method in which I compare 2 values and if they are equal I store the different results in an array, what happens is that the null values are printed. I would like to know how I can replace those null values with blanks or directly delete them.
public String Search(String type) {
String[] animalTypes;
animalTypes = new String[50];
for (int i = 0; i < animals.length; i ) {
if (animals[i] != null) {
while (animals[i].getClassification().equalsIgnoreCase(type)) {
animalTypes[i] = animals[i].getName();
break;
}
}
}
String printAnimalTypes = Arrays.toString(animalTypes);
return printAnimalTypes;
}
The idea would be that at the moment of storing the array it would ask if it was null and if so it would not store it so that at the moment of printing it would not print it.
CodePudding user response:
There are many types of ways you can store multiple values, they are called Collections. Arrays are great at storing values, but bad at taking one out, because they are numbered, and you can't just take one out. (see above)
So instead just use a list, and convert it into an array if you must.
public String Search(String type) {
List<String> animalList = new ArrayList<>();
for (int i = 0; i < animals.length; i ) {
if (animals[i] != null) {
while (animals[i].getClassification().equalsIgnoreCase(type)) {
animalList.add(animals[i].getName());
break;
}
}
String[] animalTypes = animalList.toArray(new String[0]);
String printAnimalTypes = Arrays.toString(animalTypes);
return printAnimalTypes;
CodePudding user response:
You code initializes the array and then selectively puts the elements in it (leaving the interm values as null). For example - if the animals at index 0
and 3
match the type, only the array elements 0
and 3
will be initialized with the name (leaving the values at 1
and 2
as null
).
One way you can handle this is to put a separate index/counter variable that you increment only if there is a match.
Another way is to replace your while
condition with an if
condition and add a 'blank' in the else part