-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 withnull
). Usec < arrayNome.length
which guarantees that it will always travel all, regardless of the amount.– hkotsubo
It worked, thank you!
– Abraão Paiva