How to define an enum “WeatherCondition” in Java with icon file names?
I am currently engaged in a particular task that is related to developing a weather Monitoring application that needs to categorize different weather conditions. Each weather condition should be associated with a particular icon to display the user interface of the application. The weather conditions which I need to support are SUNNY, CLOUDY, RAUNY, and SNOWY. How can I define an enum “WeatherCondition” in Java programming language where each value should be associated with the icon file name?
In the context of Salesforce, here is the best approach given:-
// Define the enum WeatherCondition
Public enum WeatherCondition {
SUNNY(“sunny_icon.png”),
CLOUDY(“cloudy_icon.png”),
RAINY(“rainy_icon.png”),
SNOWY(“snowy_icon.png”);
Private final String iconFileName;
// Private constructor to initialize the icon file name for each enum value
WeatherCondition(String iconFileName) {
This.iconFileName = iconFileName;
}
// Public method to retrieve the icon file name associated with each weather condition
Public String getIconFileName() {
Return iconFileName;
}
}
// Main class to demonstrate the usage of the WeatherCondition enum
Public class WeatherApp {
// Method to print the icon file names for all weather conditions
Public static void printWeatherIcons() {
For (WeatherCondition condition : WeatherCondition.values()) {
System.out.println(condition.name() + “ icon: “ + condition.getIconFileName());
}
}
// Main method to run the application
Public static void main(String[] args) {
System.out.println(“Weather conditions and their icons:”);
printWeatherIcons();
}
}
Detailed explanation
Enum definition
Values: the enum “weather condition” includes four values SUNNY, CLOUDY, RAINY, SNOWY.
Fields: Each annum value has an associated icon file name which is stored in the private final field “iconame”.
Constructor: The constructor “weatherCondition” would initialize the “iconFileName” field.
Method: the method “getIconName()” would return the icon name file for the specific enum values.
Main class
Method: This method would iterate over all enum values by using Weather condition value () which would print each condition name and associate it with an icon file name.
Main method: The main method would call print Weather Icon to demonstrate the usage of the enum and print the details.
Output example:-
When you run the “WeatherApp” class, the output would be the following:-
Weather conditions and their icons:
SUNNY icon: sunny_icon.png
CLOUDY icon: cloudy_icon.png
RAINY icon: rainy_icon.png
SNOWY icon: snowy_icon.png
This code would provide a clear, complete example of how you can define and use an enum in java which is associating each value with additional properties and also demonstrating how you can retrieve and use those properties.