As you may have guessed, your problem is with trying to create an enum
constant outside the enum through Mois(mount)
. An enum
guarantees that there is always exactly 1 instance of each constant in your JVM, so you cannot do that.
Fortunately, in your case there is an easy way around it. Your months are numbered 1 through 12. At the same time, all the constants in an enum
are already numbered, only from 0 (so through 11 in this case). So to get Mois
number mount
, just do:
Mois moi = Mois.values()[mount - 1];
values()
returns an array containing all the constants. I subtract 1 from mount
to convert from your 1-based numbering to Java’s 0-based.
There are a few minor issues in your code too. Better fix them to get the thing working:
- You cannot do
public Mois(int k)
in an enum
; your IDE probably already told you. An enum
constructor must be private. I understand why you tried public
, but with the fix above we no longer need that, we can just declare it private
.
- Your
toString
method calls itself recursively leading to an infinite recursion. Just delete the method. enum
s have default toString
methods that do as you expect.
- You have two declarations of a variable named
mois
. Just delete the instance variable private Mois mois;
. Again, with the above fix you don’t need it.
Now when I call date("2017-01-15")
, I get January 15, 2017
.
I understand that you are not allowed to use standard classes, so I suggest that the above is your answer. For anyone else, in the real world one would probably want to use Java’s standard classes for date manupulation. Since Java 8, one should do something like:
String output = LocalDate.parse(inputDateString, DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT))
.format(DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ROOT));
Choose an appropriate locale (or leave out the two locale arguments to use the computer’s defaut). If you wanted day-of-month to have prefixed zero for days 1 through 9 (01
through 09
), you would use dd
in the second formatting pattern.