How to fill null spaces in a java array?

Asked

Viewed 42 times

-1

I need to store a person’s first and last name within a variable.

I was able to separate String words within an array and take the first name (by index 0) - and now I would like to know how to get the last name.

        String nomeCompleto; //variável para pegar o nome completo
        System.out.println("Digite o nome ");
        nomeCompleto = sc.nextLine(); //lendo nome

        //separando o nome completo em nomes separados para obter o primeiro e último nome
        String nome = nomeCompleto; 
        String arrayNome[] = new String[5];
        arrayNome = nome.split(" ");

        for (int c = 0; c < 5; c++) {
            System.out.println(arrayNome[c]);
        } //mostrando os valores dentro do array

The program is reading all the values, however, when arriving at an index that does not exist value, the program gives error - I believe that this happens to be null.

  • c < 5 - Who guarantees that the array will always have 5 elements? If you have more, you will be ignoring the rest, if you have less, you will give index out of bound error (that is, nothing to do with null). Use c < arrayNome.length which guarantees that it will always travel all, regardless of the amount.

  • It worked, thank you!

1 answer

2

Do not fix the value of the name in 5 because not every name will have this size, for example "André Luiz Santos" would have the size of 3 only.

Since you are working with an array, just take the last element that is the size of the -1 array. If size is 3 the index of the last element of the array is 2.

Another point to consider is that the array may be empty and in this case the size of the generated array would be 0 and the last element in this model would look for 0 - 1 and also gives error, so I recommend looking for the last name only if the size of the arrayName is greater than 1.

Try this way

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String nomeCompleto; //variável para pegar o nome completo
    System.out.println("Digite o nome ");
    nomeCompleto = sc.nextLine(); //lendo nome

    //separando o nome completo em nomes separados para obter o primeiro e último nome
    String nome = nomeCompleto;
    //Linha removida pois nem todo nome tem é composto por 5 nomes
    // String arrayNome[] = new String[5];

    //inicia a array com o tamanho adequado para cada nome
    String[] arrayNome = nome.split(" ");

    if(arrayNome.length > 1) {
        String ultimoNome = arrayNome[arrayNome.length - 1]; //Ultimo elemento do array
        System.out.println("O ultimo nome é " + ultimoNome);
    }
}

Browser other questions tagged

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