To change the enum value to int

Asked 1 years ago, Updated 1 years ago, 64 views

public enum TAX {
    NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

    private int value;
    private TAX(int value){
        this.value = value;
    }
}

TAX var = TAX.NOTAX;

public int getTaxValue()
{
  // What am I supposed to do here?
  // Should I return (int)var; like this?
}

I created a method called getTaxValue() that returns the TAX value if there is a code like this, but I don't know how to return the value of TAX, which is enum. What should I do?

java enum

2022-09-21 16:49

1 Answers

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

You can define a method called getValue in enum like this.


2022-09-21 16:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.