当我尝试在main方法中调用daysInaMonth方法时,出现此错误:
DaysInMonth.java:34: error: missing return statement
}
^
1 error
我做错了什么?为什么方法调用不起作用?我确保两种方法都返回正确的数据类型。这是我的班级文件:
import java.util.Scanner;
public class DaysInMonth {
public String daysInaMonth (int year_number, String month_name) {
if(year_number % 4 != 0 || month_name != "February") {
switch(month_name) {
case "January":
case "March":
case "May":
case "July":
case "August":
case "October":
case "December":
System.out.print("31");
break;
case "April":
case "June":
case "September":
case "November":
System.out.print("30");
break;
case "February":
System.out.print("28");
break;
default:
System.out.print("Please input ");
break;
}
}
else {
System.out.print("29");
}
}
public String main(String[] args) {
Scanner scnr = new Scanner(System.in);
String month = " ";
int year = 0;
month = scnr.nextLine();
year = scnr.nextInt();
return daysInaMonth(year, month);
}
}
答案 0 :(得分:3)
问题是你的daysInaMonth()
方法没有返回任何内容。签名表示它应该返回String
。
但是,该方法目前设置为进行打印,而不是返回String
。
因此,最简单的方法是将方法的签名更改为:
public void printDaysInAMonth (int year_number, String month_name) {
// ... your code ...
}
然后,在main()
中,而不是:
return System.out.print(daysInAMonth(year, month));
只是做:
printDaysInAMonth(year, month);
在daysInaMonth()
中,将对System.out.print()
的每个引用更改为return语句,以返回String
。同时删除break
,因为您return
,这将不再有用。例如:
case "December":
return "31";
现在在main()
,您可以致电daysInaMonth()
,它会返回String
值:
String stringThatWeGotBack = daysInaMonth(year, month);
System.out.println(stringThatWeGotBack);
或者只是:
System.out.println(daysInaMonth(year, month));
答案 1 :(得分:1)
将System.out.print
方法中的return
替换为daysInaMonth
语句。
另外,在main方法中将return daysInaMonth(year, month);
更改为System.out.print(daysInaMonth(year, month))
。