Sort array alphabetically and show only first name of each item

3

I am totally a layman in Java, I wanted help in completing an exercise.

The statement is this:

  

"write a program that receives an array with the name   complete of 10 people and present an array with only the first name   of each person and in this array of only names they must be   listed in alphabetical order. "

     

Example: Joao da Silva, Felipe Santos, Adriano Kramer .... (first   array). Result: Adriano, Felipe, Joao ... (second array).

     

Take only the first name before space as first name!

I have already done the writing part of the ten names (I put 3 in the code to speed up the tests, then change to 10).

I'm having a hard time finishing the part that shows only the first name. The teacher said that he could use the command split() , even so I could not do this part of the exercise.

Here is my code:

package exercicio2;

import java.util.Scanner;
import java.util.Arrays;

public class ListaNomes {

    public static void main(String[] args ) {

        Scanner input = new Scanner(System.in);
        String nome[] = new String[3];

        for(int i = 0; i<nome.length; ++i) {

        System.out.print("Digite o nome do " +(i+1) + "º aluno: ");
        nome[i] = input.nextLine();

        }

    System.out.println(" ");

    Arrays.sort(nome);

    for (int i=0; i< nome.length; i++){

        System.out.print(nome[i]+"\n");         
    }

    input.close();

    }       
}
    
asked by anonymous 28.08.2016 / 19:47

1 answer

4

Try this:

public static void main (String[] args) {

    Scanner input = new Scanner(System.in);
    String nome[] = new String[3];

    for(int i = 0; i<nome.length; ++i) {

    System.out.print("Digite o nome do " +(i+1) + "º aluno: ");
    nome[i] = input.nextLine();

    }

    System.out.println(" ");

    Arrays.sort(nome);

    String[] firstNames = new String[nome.length];

    for (int i=0; i< nome.length; i++){

        firstNames[i] = nome[i].split("\s")[0];         
    }

    for(String firstName : firstNames){
        System.out.println(firstName);
    }
}

split breaks String into a new string array, with the first and last name (which are the values separated by the space). The first index of this array is the name.

See working at IDEONE .

Nothing prevents you from displaying the names directly in the first loop, but since the exercise requires a new array with only names, I did the first to separate and store the names, and the second to display them.

    
28.08.2016 / 20:43