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

Java 类型不匹配:无法从int转换为String,java,Java,因此,我不断得到类型不匹配:当我试图在返回中放入某些内容时,无法从int转换为String;代码怎么了?我必须使用getMessage int numEggs,因为这是我得到的问题的一部分 当我尝试在返回中放入某些内容时,无法从int转换为String 该方法要求您返回一个字符串。所以你不能这样做: public String getMessage (int numEggs) { int a = numEggs/12; int b = numEggs%12; if (

因此,我不断得到类型不匹配:当我试图在返回中放入某些内容时,无法从int转换为String;代码怎么了?我必须使用getMessage int numEggs,因为这是我得到的问题的一部分

当我尝试在返回中放入某些内容时,无法从int转换为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;
    }
}
但你可以做到:

return 1; //ie 1, does not get automatically converted to "1"
我没有得到类型不匹配:无法从int转换为String,但错误是:此方法必须返回String类型的结果

方法中缺少return语句:

return "I'm a String";

您需要返回字符串吗?
如果您只想打印,只需将返回类型设为空并删除底部的返回。

如果您想返回字符串:

公共字符串getMessage int numegs{

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

如果你想在控制台上打印,那么

public void getMessage int numegs{

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

}

我认为此练习的目的是让您返回消息,而不是像您那样将其打印到屏幕上。这是否意味着我应该使用return而不是System.out.println?如果将返回类型更改为void@IswantoSanreturn语句是不必要的,删除它只会提高可读性。