How to capture the first letter of a String name and if the letter is 'C' save the name in a vector?

7

I have an algorithm that reads a name from any person and if the name starts with the letter "C" it should capture the name and save it to the vector. I've tried every way but I can not do it.

public static void main(String[] args) {

    String nome;
    String []soC = new String[10];
    Scanner sc = new Scanner(System.in);

    for(int c = 0; c < soC.length; c++ ){
        System.out.println(" Digite o seu nome:");
        nome = sc.next();
        if(nome){

        }
    }
}   

I did so:

public static void main(String[] args) {

    String nome;
    String []soC = new String[10];
    Scanner sc = new Scanner(System.in);
    int total = 0;
    for(int c = 0; c < soC.length; c++ ){
        System.out.println(" Digite o seu nome:");
        nome = sc.next();
        if(nome.charAt(0) == 'C'){
            total++;
            soC[total] = nome;
        }
    }

    for(int i = 0; i<=total; i++){
        System.out.println(soC[i]);
    }
}

But it's printing like this:

null
Carla
Carlina
Clau
Craudio

How do I get this null?

    
asked by anonymous 19.01.2016 / 15:35

2 answers

3

Attempts to use the charAt method, this method returns the char of the String according to the specified index, in this case index 0 which is the first letter of the name.

public static void main(String[] args) {

    String nome;
    String []soC = new String[10];
    Scanner sc = new Scanner(System.in);
    int total = 0;
    for(int c = 0; c < soC.length; c++ ){
        System.out.println(" Digite o seu nome:");
        nome = sc.next();
        if(nome.charAt(0) == 'C'){
            soC[total] = nome;
            total++;
        }
    }

    for(int i = 0; i<=total; i++){
        if (soC[i] != null){
            System.out.println(soC[i]);
        }
    }
} 
    
19.01.2016 / 15:47
1

To remove null you only need to change the moment when the total variable is incremented:

    for(int c = 0; c < soC.length; c++ ){
    System.out.println(" Digite o seu nome:");
    nome = sc.next();
        if(nome.charAt(0) == 'C')
        {
        soC[total++] = nome;
        }
    }
    
20.01.2016 / 12:16