-6

At first, I apologize for my bad English.

I want to get message with serial number using enum type. Example is as follows, How can I get my expect result?? Or is there a good way?? What I want to do is just a adding serial number to "start" like "start 0" and when a1 instance invoking callEnd I wanto get "end 0"

public enum State{
    START("start"),
    END("end");    

    public String msg;  

    private State(String msg){
       this.msg = msg;
    }
}

public class A{

   public void callStart(){
      System.out.println(State.START.msg);
   }

   public void callEnd(){
      System.out.println(State.END.msg);
   }

   public static void main(String[] args){
       A a1 = new A();
       A a2 = new A();

       a1.callStart(); // I wanna get start 0 here
       a2.callStart(); // I wanna get start 1 here     
       a1.callEnd();   // I wanna get end 0 here
       a2.callEnd();   // I wanna get end 1 here
   }
}
veljp
  • 9
  • 1
  • 4
  • 2
    Sorry, no idea what you are talking about. Could you try to explain it a little bit more? – Florian Schaetz Mar 25 '16 at 14:53
  • `msg` is `private`. You either have to create a getter method, or make it `public` (either way I would also make it `final` too, so it can't be modified). – Siguza Mar 25 '16 at 14:54
  • 1
    I'm noticing that `msg` is almost the same as the value of the enum. Why not use either [`name()` or override the `toString()`](http://stackoverflow.com/questions/13291076/java-enum-why-use-tostring-instead-of-name)? – Laurel Mar 25 '16 at 14:57

1 Answers1

2

The fact that it's an enum makes no difference - you just need a field to keep track of the number.

You could add a counter, though @PeterLawrey suggests should avoid making enum values mutable unless this is the simplest solution.

public enum State{

    START("start"),
    END("end");

    private int counter = 0;

    private String msg;

    State(String msg){
        this.msg = msg;
    }

    String getMessage() {
        return msg + " " + counter++;
    }
}

public static void main(String[] args) {
    System.out.println(State.START.getMessage());   // start 0
    System.out.println(State.START.getMessage());   // start 1
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116