Java – ‘placeholder’ character to avoid positive comparison?

I'm studying codingbat exercises for Java I encountered the following problems:

My code is like this:

public int matchUp(String[] a,String[] b){

    int count = 0;

    for (int i = 0; i < a.length; i++) {
        String firstLetterA = a[i].length() == 0
                            ? "ê"
                            : a[i].substring(0,1);
        String firstLetterB = b[i].length() == 0
                            ? "é"
                            : b[i].substring(0,1);

        if (firstLetterA.equals(firstLetterB)) {
            count++;
        }
    }
    return count;
}

My question is: which "placeholder" character is considered a good practice to avoid unnecessary comparisons between firstlettera and firstletterb?

In this case, I only assigned two different letters that are rarely used (at least in English) I try to use "(a null character, not a space) but, of course, they match each other I've also tried to use null because I don't think it can make a positive comparison, but it can also cause problems

Solution

A good practice – IMO – is conditional extension instead of using any virtual characters:

for (int i = 0; i < a.length; i++) {
    if (!a[i].isEmpty() && !b[i].isEmpty() && a[i].charAt(0) == b[i].charAt(0)) {
        count++;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>