0

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;
    }
chiagger
  • 63
  • 1
  • 8

1 Answers1

0

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];
    }
aatwork
  • 2,130
  • 4
  • 17
  • It is very likely that the result should be returned as soon as the match is found, and check for negative case is redundant. `for (int i = 0; i < letterDispari.length; i++) { if (letterDispari[i].equals(letter)) return numberDispari[i]; } return "";` – Nowhere Man Mar 20 '21 at 14:36
  • Yeah. That condition can be tweaked. I am keeping it same as the original for simplicity of understanding. – aatwork Mar 20 '21 at 14:39