Problem adding elements to the array

Asked

Viewed 70 times

-1

I am trying to add elements inside the Array through a method, but at the end of the execution it repeats the last value inserted. I made a simple code just to show the error and try to avoid this problem in more complex activities in the future.

public class Teste {
public String lista[] = new String[2];

public void adicionar(String nome) {
    for (int i = 0; i < lista.length; i++) {
        lista[i] = nome;
    }
}

public void mostrar() {

    for (String nome : lista) {
        System.out.println("Nome " + nome);
    }

}

public static void main(String[] args) {

    Teste teste = new Teste();
    teste.adicionar("Paulo");
    teste.adicionar("João");
    teste.mostrar();

}

Imagem da execução

  • The method adicionar always changes the value of all array elements...

  • In the method adicionar() here for (int i = 0; i < lista.length; i++) {lista[i] = nome;} you are instructing that first element of lista to the last receive nome. Use a Arraylist in place of Array.

2 answers

1

The problem is that in the method adicionar you roam the countryside lista filling with the String passed as parameter, then when the method is called for the second time overwrites what was in the first positions. You can change this behavior by checking if the index in question is empty and only then fill it. Once filled, the loop is broken:

// ...

public void adicionar(String nome) {
  for (int i = 0; i < lista.length; i++) {
    if (lista[i] == null) {
      lista[i] = nome;
      break;
    }
  }
}

// ...

If you have no restriction on just using array, I advise you to use a HashSet to save values, simplifying your code:

import java.util.HashSet;
import java.util.LinkedHashSet;

public class Teste {

  public HashSet<String> lista = new LinkedHashSet();

  public void adicionar(String nome) {
    lista.add(nome);
  }

  public void mostrar() {
    for (String nome : lista) {
      System.out.println("Nome " + nome);
    }
  }

  public static void main(String[] args) {

    Teste teste = new Teste();
    teste.adicionar("Paulo");
    teste.adicionar("João");
    teste.mostrar();

  }
}

0

If you really want to use an array, the way is for you to control the position where the next one should be inserted (taking care not to oversize the array). Something like that:

public class Teste {
    private String lista[] = new String[2];
    private int adicionados = 0; // conta quantos foram adicionados

    public void adicionar(String nome) {
        if (this.adicionados == this.lista.length) { // já lotou o array
            System.out.println("não é possível adicionar mais nomes");
        } else { // ainda tem espaço
            this.lista[this.adicionados] = nome;
            this.adicionados++;
        }
    }

    public void mostrar() {
        for (int i = 0; i < this.adicionados; i++) {
            System.out.println("Nome " + this.lista[i]);
        }
    }
}

So you don’t need to make one loop to insert (looking for some space, until finding, as suggested to another answer), Just put your name in the right position. It’s okay that in this case the array is small, but for larger arrays this becomes impractical (and why go through everything again if I already know that the first positions will be occupied? doesn’t make sense).

The difference is that to show, you can’t do the loop throughout the array, and yes to the amount of names that have been entered. So you avoid printing a lot of null (when initializing the array with new String[2], his values are set to null).


That being said, if you want to add "free" names, without worrying about the size, you can use a list:

public class Teste {
    private List<String> lista = new ArrayList<>();

    public void adicionar(String nome) {
        this.lista.add(nome);
    }

    public void mostrar() {
        for (String nome : this.lista) {
            System.out.println("Nome: " + nome);
        }
    }
}

Or, if you want to limit the maximum number of names you can have on the list:

public void adicionar(String nome) {
    if (this.lista.size() == 10) { // supondo que só pode ter 10 no máximo
        System.out.println("não é possível adicionar mais nomes");
    } else { // ainda tem espaço
        this.lista.add(nome);
    }
}

The other answer suggested to use LinkedHashSet, which also works. The difference is that the Set does not allow repeated elements, while the List allows (see what makes the most sense for your case).

Browser other questions tagged

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