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)
因为它是我给出的问题的一部分。
答案 0 :(得分:0)
当我尝试在返回中放入某些内容时,
无法从int转换为String
该方法希望您返回一个String。所以你做不到:
return 1; //ie 1, does not get automatically converted to "1"
但你可以这样做:
return "I'm a String";
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
你需要返回一个字符串吗? 如果您只是想打印,只需将返回类型设为无效并删除底部的“返回”。
答案 3 :(得分:0)
如果要返回String:
public String 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;
}
如果你想在consolse中打印它,那么
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+".");
}
}