繁体   English   中英

类型不匹配:无法从int转换为String

[英]Type mismatch: cannot convert from int to String

public String getMessage (int numEggs) {

    int a = numEggs/12;
    int b = numEggs%12;

    if ( numEggs < 0) {
        System.out.println("Invalid number");
    } else {
        System.out.println("Your number of eggs is "+ a +" dozen(s) and "+ b+".");
        return;
    }
}

因此,我不断收到Type mismatch: cannot convert from int to String当我尝试在返回值中输入内容时, Type mismatch: cannot convert from int to String 代码有什么问题? 我必须使用getMessage (int numEggs)因为它是我给出的问题的一部分。

无法将int转换为String”,当我尝试在返回内容中输入内容时,

该方法要求您返回一个字符串。 所以你不能做:

return 1; //ie 1, does not get automatically converted to "1"

但是您可以:

return "I'm a String";

我没有看到Type mismatch: cannot convert from int to String但是错误是: This method must return a result of type String

您在方法中缺少return语句:

public String getMessage(int numEggs) {

    int a = numEggs / 12;
    int b = numEggs % 12;

    if (numEggs < 0) {
        return "Invalid number";
    } else {
        return "Your number of eggs is " + a + " dozen(s) and "
                + b + ".";          
    }
}

即使我将getMessage返回类型更改为void也不会给我Type mismatch: cannot convert from int to String

public void getMessage(int numEggs) {

    int a = numEggs / 12;
    int b = numEggs % 12;

    if (numEggs < 0) {
        System.out.println("Invalid number");
    } else {
        System.out.println("Your number of eggs is " + a + " dozen(s) and "
                + b + ".");
        return;
    }
}

您需要返回一个字符串吗? 如果您只想打印,则只需将返回类型设置为空并删除底部的“ return”即可。

如果要返回字符串:

公共字符串getMessage(int numEggs){

int a = numEggs/12;
int b = numEggs%12;
String strReturn = "";

if ( numEggs < 0) {
    strReturn = "Invalid number";
} else {
    strReturn = "Your number of eggs is "+ a +" dozen(s) and "+ b+".";

}
return strReturn;

}

如果您想将其打印出来,那么

公共无效的getMessage(int numEggs){

int a = numEggs/12;
int b = numEggs%12;

if ( numEggs < 0) {
    System.out.println("Invalid number");
} else {
    System.out.println("Your number of eggs is "+ a +" dozen(s) and "+ b+".");
}

}

暂无
暂无

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

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