1
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当我尝试在回报中放入一些东西时,我会不断得到;代码有什么问题?我必须使用getMessage (int numEggs)它,因为它是我提出的问题的一部分。

4

4 回答 4

0

当我尝试将某些内容放入返回时,无法从 int 转换为 String,

该方法期望您返回一个字符串。所以你不能这样做:

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

但你可以这样做:

return "I'm a String";
于 2013-04-01T02:53:57.827 回答
0

我不明白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;
    }
}
于 2013-04-01T02:55:38.330 回答
0

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

于 2013-04-01T02:58:09.500 回答
0

如果你想返回一个字符串:

公共字符串 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+".");
}

}

于 2013-04-01T17:23:59.650 回答