Incompatible Types String and Char

前端 未结 4 1948
挽巷
挽巷 2021-01-17 01:13

I\'m not sure why I\'m getting this error. I think the code in general is okay although I\'m sure there is a shorter way then using all the else ifs. The problem is it says

相关标签:
4条回答
  • 2021-01-17 01:40

    R2D2 is of type String while the single quotes around a character (as in 'a') makes it a character literal. Strings cannot be assigned, or compared to a, character. That's the reason.

    There are two kinds of problems in the code.

    1. `R2D2= lineOne.charAt(i); // a character being assigned to a String variable`
    

    Solution: R2D2 = Character.toString(lineOne.charAt(i));

    2. `if (R2D2== 'a'|| R2D2=='A')` //strings being compared with char literals.
    

    Solution: if (R2D2.equals("a")|| R2D2.equals("A"))

    FYI, To improved the maintenance you can also do.

    if(R2D2.equalsIgnoreCase('a'))
    
    0 讨论(0)
  • 2021-01-17 01:41

    char is not String. Declare R2D2 as char

    char R2D2 = '';
    

    To check vowel make a method like below and reuse this method at for loop and count the vowel occurrence:

    static boolean isVowel(char ch) {
        ch = Character.toLowerCase(ch);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            return true;
        }
        return false;
     }
    
    0 讨论(0)
  • 2021-01-17 01:55
        String lineOne,  R2D2 = "";
    

    R2D2 is a string and you are comparing with a char if (R2D2== 'a'|| R2D2=='A')

    try this

    for (int i = word -1; i>= 0; i--) { R2D2= lineOne.charAt(i);

            if (R2D2=="a"|| R2D2=="A")
            count++;
            else if (R2D2=="e"||R2D2=="E")
            count++;
            else if (R2D2=="o"|| R2D2=="O")
            count++;
            else if (R2D2=="u"||R2D2=="U")
            count++;
            else if (R2D2=="y"||R2D2=="Y")
            count++;
    
    }
    

    One side not,you should compare using .equals() instead of ==

    0 讨论(0)
  • 2021-01-17 01:55

    If you want to fix the long if chain you can do something like this:

    if (anyOf(R2D2, "AaEeIiOoUuYy".toCharArray())
    

    and later have:

    private static boolean anyOf(char in, char[] items) {
        for (int i = 0; i < items.length; i++) {
            if (in == items[i])
                return true;
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题