简体   繁体   English

错误:类型不兼容:布尔值无法转换为int

[英]error: incompatible types: boolean cannot be converted to int

I'm getting the error: incompatible types: boolean cannot be converted to int error while compiling the android app in Android Studio. 我收到错误消息:不兼容的类型:在Android Studio中编译android应用程序时, 布尔值无法转换为int错误。 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. 提前致谢。

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.
        }
    }

Problem lies in this statement: 问题在于此语句:

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

equalsIgnoreCase() method returns a boolean value and you are assigning it to an int value. equalsIgnoreCase()方法返回一个boolean值,并且您将其分配给一个int值。 That's why it is giving this error. 这就是为什么它会给出此错误。

You can make use of Strings in switch statements and return respective int values. 您可以在switch语句中使用Strings并返回各自的int值。

https://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html 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). 您可以考虑0(FALSE)和1(TRUE)。 Or any such random value. 或任何此类随机值。

Java is not a C language, so booleans cannot be integers, they are totally different types and cannot be mixed. Java不是C语言,因此布尔值不能是整数,它们是完全不同的类型,不能混合使用。 In the 3rd line you are assigning boolean value to an int 在第三行中,您将布尔值分配给int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM