Incompatible Types String and Char

前端 未结 4 1952
挽巷
挽巷 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'))
    

提交回复
热议问题