7
I have an algorithm that reads a name of someone and if the name starts with the letter "C" should capture the name and save in the vector. I’ve tried it anyway but I can’t 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?
You remove this null by incrementing the total variable after you set the name in the vector. Or you do this: "Soc[total++] = name" or "Soc[total] = name; total++;"
– cantoni