Accessing a static array from a method in java?

时间:2017-06-09 12:56:59

标签: java arrays

I have the following static method in my main class:

static int daysMonth(int Y, int M){
    int [] month = {31, 28+(Y%4==0?1:0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return month[M-1];
}

I want to access the month array from a different method that I am creating lower in the class. I want the variable D (which will stand for days) to take the exact value of the M-1 index, but I am not sure how to access it correctly...I know this is probably a very simple thing, but I can't recall how it should be done, recommendations on things I should re-read (regarding arrays or smth in Java) are welcome!

1 个答案:

答案 0 :(得分:0)

在方法之外声明数组,然后就可以在整个类中使用它。

static int [] month = null;

static int daysMonth(int Y, int M){
    month = {31, 28+(Y%4==0?1:0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return month[M-1];
}