微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – ‘占位符’字符以避免积极比较?

我正在研究 CodingBat exercises for Java.我遇到了以下问题:

Given 2 arrays that are the same length containing strings,compare the 1st string in one array to the 1st string in the other array,the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length,including 0.

我的代码是这样的:

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;
}

我的问题是:哪个“占位符”字符被认为是一种良好的做法,可以避免在firstLettera和firstLetterB之间进行不必要的比较?

在这种情况下,我只分配了两个很少使用的不同字母(至少用英文).我尝试使用”(一个空字符,而不是空格)但当然,它们相互匹配.我也尝试过使用null,因为我认为它无法进行正面比较,但这也会导致问题.

解决方法

一个好的做法 – IMO – 是条件扩展而不是使用任何虚拟字符:
for (int i = 0; i < a.length; i++) {
    if (!a[i].isEmpty() && !b[i].isEmpty() && a[i].charat(0) == b[i].charat(0)) {
        count++;
    }
}

原文地址:https://www.jb51.cc/java/120974.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐