用 Java 中的特定数值替换给定字母

Replacing given letter with a specific number value in Java

我想将一个字母作为字符串传递给此方法,它应该返回存储在与 letterDispari 数组相同的索引中但在 numberDispari 数组中的相应数字(作为字符串)。 我认为使用字符串比创建一个巨大的 switch 语句更容易。但是我不明白为什么这没有返回任何东西。

private static String toNumberDispari2(String letter) {
        String result= "";
        String[] letterDispari = {"0","1","2","3","4","5","6","7","8","9",
                "A","B","C","D","E","F","G","H","I","J","K","L","M",
                "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        String[] numberDispari = {"1","0","5","7","9","13","15","17","19","21",
                "1","0","5","7","9","13","15","17","19","21",
                "2","4","18","20","11","3","6","8","12","14","16","10","22","25","24","23"};
        
        for(int i=0; i<=35; i++) {
            if (letter != letterDispari[i])
                continue;
            else if (letter == letterDispari[i])
                result = numberDispari[i];
        }
        return result;
    }

字符串是一个 Java 对象。您不能使用“=”运算符来检查两个不同的 String 对象是否具有相同的值。 “=”检查对象引用,在这种情况下会有所不同。您需要使用以下代码进行值比较。

   for(int i=0; i<=35; i++) {
        if (!letter.equals(letterDispari[i]))
            continue;
        else if (letter.equals(letterDispari[i]))
            result = numberDispari[i];
    }