[英]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.