Method that returns the amount of objects removed from an object array

Asked

Viewed 64 times

0

My method can actually remove objects from the array, but it always returns 0 the amount of removed, I have tested different amounts and it always removed from the list, but always returned 0 of removed. I would like it to return the correct amount of objects removed.

public int removerTodosClientesPorNome(String nome) {
    int quantidade = 0;
    for (int i = 0; i < listaCliente.length; i++) {
        if (listaCliente[i] != null && listaCliente[i].getNome().equals(nome)) {
            listaCliente[i] = null;
            quantidade++;
        }
    }
    return quantidade;
}
  • Put your full code.

1 answer

1

Probably or your method getNome() is returning a value other than intended or the array is empty or the item you intend to remove is not present. Without the array-related code it is not possible to evaluate precisely.

What I was able to do with this fragment of code that you published was test the execution logic, where I switched the array by a List<String> and populated listaCliente uppercase.

import java.lang.*;
import java.util.*;


public class HelloWorld
{

  public static void main(String[] args)
  {
    OtherClass myObject = new OtherClass();

    System.out.print("Foram removidos " + myObject.removerTodosClientesPorNome("J") + " itens.");
  }
}


public class OtherClass
{
  List<String> listaCliente = new ArrayList<String>();

  public OtherClass()
  {
    listaCliente.add("A"); listaCliente.add("B"); listaCliente.add("J");
    listaCliente.add("A"); listaCliente.add("B"); listaCliente.add("J");
    listaCliente.add("A"); listaCliente.add("B"); listaCliente.add("J");
  }


  public int removerTodosClientesPorNome(String nome) {
    int quantidade = 0;
    for (int i = 0; i < listaCliente.size(); i++) {
        if (listaCliente.get(i) != null && listaCliente.get(i).equals(nome)) {
            listaCliente.set(i, null);
            quantidade++;
        }
    }
    return quantidade;
  }

}

whose result was:

Foram removidos 3 itens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.