Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator == cannot be applied to java.lang.String char

I do not get any errors in NetBeans Java Application, but I do get the mentioned error when applying the code into a Android Java Project. I tried if (alpha[i].equals(c)) { but then I would get no results like I do in NetBeans, which is converting a String to Morse e.g. SOS to ... --- ...

NetBeans Java Application (works, when I type SOS I get ... --- ...):

private static String toMorse(String text) {
    char[] characters = text.toUpperCase().toCharArray();
    StringBuilder morseString = new StringBuilder();
    for (char c : characters) {
        for (int i = 0; i < alpha.length; i++) {
            if (alpha[i] == c) {
                morseString.append(morse[i] + " ");
                break;
            }
        }
    }
    return morseString.toString();
}

Android Java Project (doesn't work, when I type in a String, I get nothing):

public String toMorse(String text) {
    char[] characters = text.toUpperCase().toCharArray();
    StringBuilder morseString = new StringBuilder();
    for (char c : characters) {
        for (int i = 0; i < alpha.length; i++) {
            if (alpha[i] == c) { // error is on this line
                morseString.append(morse[i] + " ");
                break;
            }
        }
    }
    return morseString.toString();
}

Strange part is that this part of the code works in both NetBeans and Android Studio (when I type in ... --- ... I get SOS):

public String toEnglish(String text) {
    String[] strings = text.split(" ");
    StringBuilder translated = new StringBuilder();
    for (String s : strings) {
        for (int i = 0; i < morse.length; i++) {
            if (morse[i].equals(s)) {
                translated.append(alpha[i]);
                break;
            }
        }
    }
    return translated.toString();
}

alpha and morse arrays:

private String[] alpha = {"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", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "0", " "};

private String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
    "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
    "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
    "-.--", "--..", ".----", "..---", "...--", "....-", ".....",
"-....", "--...", "---..", "----.", "-----", "|"};
like image 328
MOTIVECODEX Avatar asked May 08 '15 23:05

MOTIVECODEX


1 Answers

The problem is that alpha is an array of String while c is a character. you are comparing (char == string) which obviously doesn't work like expected.

like image 191
sockeqwe Avatar answered Sep 20 '22 12:09

sockeqwe