Store the enum constants in variable -
this code works fine, question have code how store enum constant in variable, , why use enum? , statement mean housetype housetype;
? thank in advance.
import java.util.scanner; public class homebuying { public enum housetype{unknown,singlefamily,townhouse,condominium}; public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("enter type of house want purchase"); //1.single family/n" " 2. townhouse/n" " 3. condominium/n"); int choice = input.nextint(); housetype housetype; switch(choice) { case 1: housetype = housetype.singlefamily; break; case 2: housetype = housetype.townhouse; break; case 3: housetype = housetype.condominium; break; default: housetype = housetype.unknown; break; } system.out.println(housetype); }
the code snippet provided stores enum value in variable.
housetype housetype; //declaration of variable of type housetype (means can store values of housetype enum) housetype = housetype.unknown; //put value housetype variable
we use enums whenever need represent values known , finite set. example if want program keep track of whether day or night, make rule , use integers, 1 represents day , 0 represents night. other numbers mean? or use boolean (again, arbitrary meaning attached false , true).
enum timeperiod{ day, night }
enums represent better alternative letting explicit values mean. not convenience - being explicit in intentions makes program readable others.
Comments
Post a Comment