A placeholder to avoid a positive comparison?

I am working on CodingBat exercises for Java . I came across the following question:

Given 2 arrays with the same length containing strings, compare the 1st row in one array with the 1st row in another array, 2nd and 2nd, and so on. Count the number of times when two lines are not empty and start with the same char. Strings can be any length, including 0.

My code is:

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 good practice to avoid an undesirable comparison between firstLetterA and firstLetterB ?

In this case, I just assigned two different letters, which are rarely used (at least in English). I tried just using '' (empty character, not space), but, of course, they match each other. I also tried using null for both, because I suggested that it cannot be compared positively, but this also causes problems.

+6
source share
1 answer

Good practice - IMO is an extension of the if condition and generally no use of any dummy 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++; } } 
+9
source

Source: https://habr.com/ru/post/985614/


All Articles