0

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!

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Ryne Ignelzy
  • 137
  • 1
  • 2
  • 13
  • 1
    month is a local variable and its not static. If you want to access it in other methods you have to declare it outside of any method as a field of a class, or make sure you pass the local variable to wherever you need it. Further reading: https://stackoverflow.com/questions/20671008/what-is-the-difference-between-a-local-variable-an-instance-field-an-input-par – OH GOD SPIDERS Jun 09 '17 at 13:00
  • I think you need to call the method from another class as you have given description you need to assign value to variable D on the basis of passed value of M from another class. So here you can make you method public and import the class to use the method. – Sanket Makani Jun 09 '17 at 13:03
  • Its java. Make it an own class. And pass the instance through your methods. – JacksOnF1re Jun 09 '17 at 13:12

1 Answers1

0

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 Lama
  • 21
  • 4
  • So If i leave it outside of the method, should I access it this way? D = month[M-1]; ? – Ryne Ignelzy Jun 09 '17 at 13:16
  • Yes you can. Altough i would recommend you read about how constructors and encapsulation works, as it is not the best practice to use static operators everywhere. – The Lama Jun 09 '17 at 13:21