shiki shiki - 1 month ago 11
Java Question

java : how to get element from a list of array that has distinctive first characters

i have an array of

String [] animals = {"cat", "cheetah", "tiger","shark"}


i wanted to print only tiger and shark,
i have tried to code but it print duplicates of cat and cheetah too

below is the code i attempted

public static String[] getDistinctives(String list[]){

String [] samefirst = new String [list.length];

for(int i = 0; i< list.length ; i++){
for(int j = 0; j< list.length ; j++){
if(list[i].charAt(0) == list[j].charAt(0)){
System.out.println(list[i]);
}
}
}
return samefirst;
}


it gives output off

cat
cat
tiger
shark
cheetah
cheetah


but i only want

tiger
shark


any help would be greatly appreciated!! thank you!!

Answer
public static String[] getDistinctives(String list[]){

String [] samefirst = new String [list.length];


for(int i = 0; i< list.length ; i++){
    int flag=0;
    for(int j = 0; j< list.length ; j++){   
        if( (list[i].charAt(0) == list[j].charAt(0)) && (i!=j) ){
            flag=1;
          }
}
if(flag==0)
{
 System.out.println(list[i]);   
}
}
 return samefirst;
 }

Try this. I hope this is what you want.

Comments