简体   繁体   中英

Error with java enum getter converting to int

So I read a few articles here on stackoverflow and feel like I got most of it working, but they don't usually have an example on how to use the getters/setters

I'm super close to figuring out this issue just having a hard time figuring out this last part

Currently all stores in a program i'm using is using openShop(id); but i'd like to be able to use openShop("GENERAL_STORE"); because that is much more maintainable and easy to see without having to look up the id.

Any ideas what I'm doing wrong?

private enum shopName {
    GENERAL_STORE(577);

    private final int id;
    shopName(int id) {
        this.id = id;
    }
    public int getId() {
        return this.id;
    }
};

public void openShop(String name) {
    int shopId = shopName(name).getId(); //line with error
    //int shopId = shopName.shopName(name).getId(); //I've also tried this
    openShop(shopId);
}
public void openShop(int id) {
    /* blah */
}

Here is the error i'm getting

$ ./compiler.sh
file.java:#: error: cannot find symbol
    int shopId = shopName(name).getId();
                 ^
  symbol:   method shopName(String)
  location: class File
1 error

shopName(name) doesn't do what you think it does. This code is trying to invoke method shopName and pass name as argument, but you don't have such method.

If you want to get shopName enum based on provided name use shopName.valueOf(name) . So your code should probably look like:

int shopId = shopName.valueOf(name).getId();

Also be aware that this method will throw IllegalArgumentException if you will not provide proper name.

Also enum is considered as type , so its name should start with uppercase like other Java (non-primitive) types. So change shopName to ShopName .

You say openShop("GENERAL_STORE") is more maintainable, but openShop(ShopName.GENERAL_STORE) (or the shorter openShop(GENERAL_STORE) ) would be even more maintainable, because the compiler would catch typos.

The is one of the main purposes of enums.

public enum ShopName {
    GENERAL_STORE(577);

    private final int id;
    private ShopName(int id) {
        this.id = id;
    }
    int getId() {
        return this.id;
    }
};

public void openShop(ShopName name) {
    openShop(name.getId());
}
public void openShop(int id) {
    /* blah */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM