2015-10-07 50 views
-3

我已经编写了一个静态方法,该方法接受一个单一的int参数,该参数是数字月份并返回给定月份中的天数。因此,1的参数将返回31,因为1月有31天,而参数2会返回28,因为2月有28天,等等。无法在主要方法中调用静态方法

但是,当我尝试在我的主要方法中调用静态方法时,出现错误消息void type not allowed here.有人可以帮我弄清楚我做错了什么吗?这是我到目前为止:

public class Days { 
    public static void main(String[] args) { 

     System.out.println(daysInMonth(1)); 

    } 
    public static void daysInMonth(int month) { 
      if (month==1||month==3||month==5||month==7||month==8||month==10||month==12) 
     System.out.println("31"); 
     else if (month==4||month==6||month==9||month==11) 
     System.out.println("30"); 
     else if (month==2) 
     System.out.println("28"); 
    } 
} 
+5

你知道'return'值和方法调用之间的差异int值打印标准输出的东西? –

+0

你有两个选择。或者只是调用'daysInMonth(1)'而不用周围的'println'调用或者'daysInMonth(...)'返回'String' –

+0

正如@SotiriosDelimanolis指出的,在'main'方法中,你调用'println' 'daysInMonth'方法的返回值,但该方法不返回值。该方法可以完成所有的打印,所以你的'main'方法不需要打印。或者'daysInMonth'方法应该返回一个具有天数的'int',并将'println'保存在'main'方法中。 – Colselaw

回答

4

您的方法是void。您不能print a void值。你可以改变

System.out.println(daysInMonth(1)); 

daysInMonth(1); 

变化daysInMonth返回像

public static int daysInMonth(int month) { 
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 
      || month == 10 || month == 12) 
     return 31; 
    else if (month == 4 || month == 6 || month == 9 || month == 11) 
     return 30; 
    return 28; 
}