简体   繁体   中英

How to get values for specific items in enum array in Java?

Continuing on from this post I've been looking into and messing around with enums a bit, and now I've managed to create an enum that holds the values I want and outputs them in the way I want, now I'd just like to know how I could get the same output but for a single item rather than every item. Again, I'm very new to Java so a simple explanation as to how and why would be greatly appreciated.

public class PeriodicTable {

    public enum Element {
        Lithium("Li", "Alkali Metals", 6.941),
        Iron("Fe", "Transition Metals", 55.933);
        private String symbol;
        private String group;
        private Double weight;

        private Element(String symbol, String group, Double weight) {
            this.symbol = symbol;
            this.group = group;
            this.weight = weight;
        }
    }

    public static void main(String[] args) {
        for(Element cName : Element.values()) {
            System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);
        }
    }
}

You can use the valueOf method passing in the user input to retrieve the enum:

Element ele = Elements.valueOf(input);

And then you can use your print statement to print the info:

Element cName = Element.valueOf("Iron");
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);

Output:

Element: Iron (Fe)
Group: Transition Metals
Atomic Weight: 55.933

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