Help enumerations in Java

Is it possible for the enumeration to change its value (internally)? It may be easier to understand the meaning of the code:

enum Rate {
    VeryBad(1),Bad(2),Average(3),Good(4),Excellent(5);

    private int rate;

    private Rate(int rate) {
        this.rate = rate;
    }

        public void increaterating() {
            //is it possible to make the enum variable increase?
            //this is,if right Now this enum has as value Average,after calling this
            //method to have it change to Good?
       }
}

This is what I want to achieve:

Rate rate = Rate.Average;
System.out.println(rate); //prints Average;
rate.increaserating();
System.out.println(rate); //prints Good

thank you

Solution

Yes You can simply call

rate = Rate.Good;

For this particular case But I think what you really want is the succession function

Here you are:

public class EnumTest extends TestCase {
    private enum X {
        A,B,C;
        public X successor() {
                return values()[(ordinal() + 1) % values().length];
        }
    };

    public void testSuccessor() throws Exception {
        assertEquals(X.B,X.A.successor());
        assertEquals(X.C,X.B.successor());
        assertEquals(X.A,X.C.successor());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>