简体   繁体   中英

Accessing a static array from a method in java?

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!

Declare the array outside of the method, then you can use it in the entire class.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM