error: incompatible types: boolean cannot be converted to int

烈酒焚心 提交于 2021-02-17 07:09:20

问题


I'm getting the error: incompatible types: boolean cannot be converted to int error while compiling the android app in Android Studio. The problem is in only one method.

private static int get_wx_inx(String str) {
    boolean equalsIgnoreCase = str.equalsIgnoreCase("木");
    int equalsIgnoreCase2 = str.equalsIgnoreCase("火");
    if (str.equalsIgnoreCase("土")) {
        equalsIgnoreCase2 = true;
    }
    if (str.equalsIgnoreCase("金")) {
        equalsIgnoreCase2 = 3;
    }
    return str.equalsIgnoreCase("水") ? 4 : equalsIgnoreCase2;
}

I don't know what could be wrong. Can you help me to figure out the problem. Thanks in advance.


回答1:


Your question is not bit clear but you might want this:

private static int get_wx_inx(String str) {
        if(str.equalsIgnoreCase("木")) {
            return 0;
        } else if(str.equalsIgnoreCase("火")) {
            return 1;
        }else if(str.equalsIgnoreCase("土")) {
            return 2;
        } else if(str.equalsIgnoreCase("金")) {
            return 3;
        } else if(str.equalsIgnoreCase("水")) {
            return 4;
        } else {
            return 0;// write default return here. If every condition goes false then this default will be return.
        }
    }



回答2:


Problem lies in this statement:

int equalsIgnoreCase2 = str.equalsIgnoreCase("火");

equalsIgnoreCase() method returns a boolean value and you are assigning it to an int value. That's why it is giving this error.




回答3:


You can make use of Strings in switch statements and return respective int values.

https://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

As we can't have mixed type for return value. You can consider 0(FALSE) and 1(TRUE). Or any such random value.




回答4:


Java is not a C language, so booleans cannot be integers, they are totally different types and cannot be mixed. In the 3rd line you are assigning boolean value to an int



来源:https://stackoverflow.com/questions/54034507/error-incompatible-types-boolean-cannot-be-converted-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!