0

Is there any way to keep straight integer in Java Enum ?

example: i am working on a Restaurant management system. i want to know what quantity of unit of any food a customer will order (e.g 1,2,5 etc.)

so i added a combo box in my GUI where list of units will be shown as : 1, 2, 3 etc. Now, Java Enum does not allowing me to write the code like this:

   public enum UnitEnum {
      1,2,3,4,5;
   }

What least i can do is writing it as:

   public enum UnitEnum {
      _1,_2,_3,_4,_5;
   }

but it is very much odd looking. Is there any way to make it look like the first one ? ( where there is no under score ).

3
  • No, there is not. Names must start with eiter a character, a $ or an _. The question is: why not write them: ONE, TWO,...? Commented Nov 12, 2015 at 14:02
  • it's just for saving time :p see, one, two, three etc. takes so many letters to type. Commented Nov 12, 2015 at 14:05
  • Do you have to use an an enum? Why not Collections.unmodifiableSet(new TreeSet<Integer>(Arrays.asList(1, 2, 5)))? Commented Nov 12, 2015 at 14:28

3 Answers 3

6

You can do:

public enum UnitEnum {
  ONE(1),
  TWO(2),
  THREE(3),
  FOUR(4),
  FIVE(5);

  public final int quantity;

  UnitEnum(int q) {
     this.quantity = q;
  }

  public int getQuantity() { return this.quantity; }
}
Sign up to request clarification or add additional context in comments.

3 Comments

And display the quantity in the combobox. private UnitEnum(int q) { quantity = q; } you assumed trivial.
i appreciate. it says constructor UnitEnum in enum UnitEnum cannot be applied to given types. required: no argument found: int reason: actual and formal argument lists differ in length.
Why not using ordinal() here instead of defining the field quantity?
0

Here is an little tutorial about enums.

The way I would choose for your Problem is something like:

//Your enum
public enum UnitEnum{ONE, TWO, THREE, FOUR, FIVE};
//Using your enum
myENUM = 1; //compilation error  
myENUM = UnitEnum.ONE // works

Comments

0

enum CheeseNuggets { X6, X9 }? Maybe not use an enum, but a class wrapping int[].

public class Ints {
    public final int[] values;

    public Ints(int... values) {
        this.values = Arrays.copyOf(values, values.length);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.