Search code examples
javaalphabet

Replacing given letter with a specific number value in Java


I wanted to pass a letter as a String to this method and it should give back the corresponding number (as String) stored in the same index as in the letterDispari array but in the numberDispari array. I thought using strings would be easier than creating a HUGE switch statement. But I don't understand why this is not returning anything.

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

Solution

  • String is a Java object. You can't use "=" operator for checking if two different String objects have same value or not. "=" checks for object reference which will be different in this case. You need to use below code to do the value comparison.

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