Results 1 to 16 of 16
  1. #1
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default How to use enhanced enumeration

    I'm trying to follow along an example in my book with an enumeration that overrides the toString method. The error is in the code comment on line 33:
    Java Code:
    //How to create and use my own enumerations
    package InnerClass.test;
    
    public class CampsiteFees {
    	public enum TypesOfCamping{
    		BACKPACK,//enumeration ordinal() constant position == 0, nightlyCampingFee == 4.99
    		TENT_NON_ELECTRIC,//enumeration ordinal() constant position == 1, nightlyCampingFee == 10.99
    		TENT_ELECTRIC,////enumeration ordinal() constant position == 2, nightlyCampingFee == 18.99
    		RV_CAMPER;//enumeration ordinal() constant position == 3, nightlyCampingFee == 24.99
    	}
    	
    	//statement that uses the enumeration and one of its constants:
    	TypesOfCamping backpack = TypesOfCamping.BACKPACK;
    	
    	//method that accepts a TypesOfCamping enumeration as a parameter:
    	public static double getCampsiteType(TypesOfCamping camp){
    		double nightlyCampingFee = 4.99;
    		if(camp == TypesOfCamping.TENT_NON_ELECTRIC){
    			nightlyCampingFee = 10.99;
    		}else if(camp == TypesOfCamping.TENT_ELECTRIC){
    			nightlyCampingFee = 18.99;
    		}else if(camp == TypesOfCamping.RV_CAMPER){
    			nightlyCampingFee = 24.99;
    		}
    		return nightlyCampingFee;
    	}
    	
    	
    	
    	@Override
    	public String toString(){
    		String s = "";
    		if(ordinal() == 0){//Error: the method ordinal() is undefined for the type CampsiteFees
    			s = "Backpacker's checkpoint (fire pit included only)";
    		}else if(this.ordinal() == 1){
    			s = "Camping without electricity (picnic table, fire pit, and drinking water "
    					+ "pump included)";
    		}else if(this.ordinal() == 2){
    			s = "Camping with electricity, picnic table, fire pit, and drinking water included";
    		}else if(this.ordinal() == 3){
    			s = "Electricity, picnic table, fire pit, and drinking water included for RVs and Campers"
    					+ "up to 200 feet in length";
    		}
    		return s;
    	}
    	
    	public static void main(String args[]){
    		//call the getCampsiteType method:
    		double nightlyCampingFee = getCampsiteType(TypesOfCamping.BACKPACK);//starting at enumeration
    		//ordinal() constant position 0
    		
    		System.out.println("This type of campsite costs $" + nightlyCampingFee + " per night.");
    	}
    
    }
    Also, I don't understand why the if statement on line 33 is the only statement in that toString method that doesn't need the
    Java Code:
    this.
    added onto the ordinal()

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: How to use enhanced enumeration

    I get errors on 33, 35, 38, and 40. Here is your error (as stated above).

    //Error: the method ordinal() is undefined for the type CampsiteFees

    Think about it. It says, "the class CampsiteFees does not have the method ordinal."
    It can be much plainer than that.

    Regards,
    Jim
    Last edited by jim829; 08-23-2016 at 04:10 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to use enhanced enumeration

    Quote Originally Posted by jim829 View Post
    Think about it. It says, "the class CampsiteFees does not have the method ordinal."
    It can be much plainer than that.
    Regarding that, the textbook's words exactly are:

    "Whenever necessary, you can override methods that an enumeration inherits from the java.lang.Object and java.lang.Enum classes. In addition, you can add your own methods. When you do that, you may want to use methods of the enumeration constants. Two of these methods are name() and ordinal()."

    name(): returns a string for the enumeration constant's name.
    ordinal(): returns an int value that corresponds to the enumeration constant's position.

    I thought all this meant that ordinal() was a special predefined method (at least I know I didn't make it). That is why, despite the clear error message, I thought maybe I was missing something.

    However, both my book and other sources also say that I won't need these methods most of the time, so if you think that these methods are not worth my time and energy to learn right now, say so now.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    "When you do that, you may want to use methods of the enumeration constants. Two of these methods are name() and ordinal()."

    ordinal() is a method on the enum.
    CampsiteFees is not an enum.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to use enhanced enumeration

    I hate static methods. I hate them. I HATE THEM

    I'm trying to figure out the best way to make enumeration constants useful, but once again, I'm fighting static method and non-static method problems. My errors and questions are in the code comments:
    CampingEnum.java:
    Java Code:
    package InnerClass.test;
    import java.lang.*;
    
    public class CampingEnum {
    	public enum TypesOfCamping{
    		BACKPACK,//enumeration ordinal() constant position == 0, nightlyCampingFee == 4.99
    		TENT_NON_ELECTRIC,//enumeration ordinal() constant position == 1, nightlyCampingFee == 10.99
    		TENT_ELECTRIC,////enumeration ordinal() constant position == 2, nightlyCampingFee == 18.99
    		RV_CAMPER;//enumeration ordinal() constant position == 3, nightlyCampingFee == 24.99
    	}
    	public static void enumValuesForTypesOfCamping(){
    		TypesOfCamping backpack = TypesOfCamping.BACKPACK;
    		TypesOfCamping tent = TypesOfCamping.TENT_NON_ELECTRIC;
    		TypesOfCamping tentElectric = TypesOfCamping.TENT_ELECTRIC;
    		TypesOfCamping rv = TypesOfCamping.RV_CAMPER;
    	}
    	/*
    	//statements that use the enumerations and one of their constants:
    	TypesOfCamping backpack = TypesOfCamping.BACKPACK;
    	TypesOfCamping tent = TypesOfCamping.TENT_NON_ELECTRIC;
    	TypesOfCamping tentElectric = TypesOfCamping.TENT_ELECTRIC;
    	TypesOfCamping rv = TypesOfCamping.RV_CAMPER;
    	*/
    }
    CampsiteFees.java:
    Java Code:
    //How to create and use my own enumerations
    package InnerClass.test;
    import java.lang.*;
    import java.util.Scanner;
    
    import static InnerClass.test.CampingEnum.*;
    public class CampsiteFees {	
    		
    	//method that accepts a TypesOfCamping enumeration as a parameter:
    	public static double getCampsiteFee(TypesOfCamping camp){
    		double nightlyCampingFee = 0.0;
    		if(camp == TypesOfCamping.BACKPACK){
    			nightlyCampingFee = 4.99;
    		}else if(camp == TypesOfCamping.TENT_NON_ELECTRIC){//if(camp == tent){
    			nightlyCampingFee = 10.99;
    		}else if(camp == TypesOfCamping.TENT_ELECTRIC){
    			nightlyCampingFee = 18.99;
    		}else if(camp == TypesOfCamping.RV_CAMPER){
    			nightlyCampingFee = 24.99;
    		}
    		return nightlyCampingFee;
    	}
    	
    	public static void printOrdinalValues(){//Despite me initializing these values (backpack, tent,
    		//tentElectric, rv) in CampingEnum.java, in a public static method, they cannot be resolved.
    		//I even included everything from CampingEnum.java in an import statement. What the hell is
    		//the freaking problem?!
    		System.out.println("Enum ordinal value for " + backpack.name() + " is " + backpack.ordinal());
    		System.out.println("Enum ordinal value for " + tent.name() + " is " + tent.ordinal());
    		System.out.println("Enum ordinal value for " + tentElectric.name() + " is " + tentElectric.ordinal());
    		System.out.println("Enum ordinal value for " + rv.name() + " is " + rv.ordinal());
    	}
    	
    	@Override
    	public String toString(){//This is a special java.lang.Object method being overridden. It won't
    		//work in the main method because the main method is static. What can I do about this?
    		String s = "";
    		if(backpack.ordinal() == 0){
    			s = "Backpacker's checkpoint (fire pit included only)";
    			System.out.println(s);
    		}else if(tent.ordinal() == 1){
    			s = "Camping without electricity (picnic table, fire pit, and drinking water "
    					+ "pump included)";
    			System.out.println(s);
    		}else if(tentElectric.ordinal() == 2){
    			s = "Camping with electricity, picnic table, fire pit, and drinking water included";
    			System.out.println(s);
    		}else if(rv.ordinal() == 3){
    			s = "Electricity, picnic table, fire pit, and drinking water included for RVs and Campers"
    					+ "up to 200 feet in length";
    			System.out.println(s);
    		}else{
    			System.out.println("Invalid campsite type. No information available.");
    		}
    		return s;
    	}
    	
    	public static void main(String args[]){
    		
    		printOrdinalValues();//I am forced to make this method static all because the main method is
    		//static.
    		double nightlyCampingFee = 0.0;
    		String s = "";
    		System.out.println("Please select the type number of the campsite you are looking for:\n"
    				+ "0: Backpack camping\n"
    				+ "1: Tent without electricity\n"
    				+ "2: Tent with electricity\n"
    				+ "3: RV parking space");
    		Scanner typeOfCampsite = new Scanner(System.in);
    		int type = typeOfCampsite.nextInt();
    		while((type != 0) && (type != 1) && (type != 2) && (type != 3)){		
    			if(type == 0){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 0
    				type = enumValuesForTypesOfCamping(backpack.ordinal());
    				nightlyCampingFee = getCampsiteFee(TypesOfCamping.BACKPACK);
    				s = toString();//error: Cannot make a static reference to the non-static method toString()
    				//from the type CampsiteFees
    				System.out.println("You selected " + backpack.name());
    				System.out.println("It includes " + s);
    				System.out.println("This type of campsite costs $" + nightlyCampingFee + " per night.");
    			}else if(type == 1){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 1
    				type = enumValuesForTypesOfCamping(tent.ordinal());
    				nightlyCampingFee = getCampsiteFee(TypesOfCamping.TENT_NON_ELECTRIC);
    				s = toString();
    			}else if(type == 2){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 2
    				type = enumValuesForTypesOfCamping(tentElectric.ordinal());
    				nightlyCampingFee = getCampsiteFee(TypesOfCamping.TENT_ELECTRIC);
    				s = toString();
    			}else if(type == 3){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 3
    				type = enumValuesForTypesOfCamping(rv.ordinal());
    				nightlyCampingFee = getCampsiteFee(TypesOfCamping.RV_CAMPER);
    				s = toString();
    			}else{
    				System.out.println("Invalid campsite type number. Please enter 0, 1, 2, or 3 and "
    						+ "try again.");
    				continue;
    			}
    		}//end of while loop				
    	}//end of main method
    }

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: How to use enhanced enumeration

    First, there is nothing wrong with static methods. You just need to know when and when not to use them.
    To avoid problems with static contexts I simply invoke a start method from main. Quite often my static main entry
    point looks like this:

    Java Code:
    class SomeClass {
        public static void main(String [] args) {
            new SomeClass().start();
        }
    
        public void start() {
          // other stuff here
        }
        // more instance methods here
    }


    I'm trying to figure out the best way to make enumeration constants useful,
    Enums are more useful when you take advantage of the fact that they are essentially a special
    type of class. I use enums either with no embellishments (as simple, enforced constants) or as follows:

    Java Code:
    enum Fruit {
       // Price per lb. and description
       APPLES(1.99, "Rome, Golden Delicious, and Gala"),
       GRAPES(2.99, "Red, Red Seedless, Green Seedless");
    
       private double price;
       private String description;
    
       private Fruit(double price, String description) {
          this.price = price;
          this.description = description;
       }
    
       public double getPrice() {
          return price;
       }
    
       public String getDescription() {
          return description;
       }
    
    }
    
    public class EnumDemo {
       public static void main(String args[]) {
          for (Fruit fruit : Fruit.values()) {
             System.out.println("Price/lb. = " + fruit.getPrice());
             System.out.println(fruit.getDescription());
             System.out.println(
                   "-----------------------------------------------------------------");
          }
       }
    }
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    Java Code:
    package InnerClass.test;
    import java.lang.*;
    
    public class CampingEnum {
    	public enum TypesOfCamping{
    		BACKPACK,//enumeration ordinal() constant position == 0, nightlyCampingFee == 4.99
    		TENT_NON_ELECTRIC,//enumeration ordinal() constant position == 1, nightlyCampingFee == 10.99
    		TENT_ELECTRIC,////enumeration ordinal() constant position == 2, nightlyCampingFee == 18.99
    		RV_CAMPER;//enumeration ordinal() constant position == 3, nightlyCampingFee == 24.99
    	}
    	public static void enumValuesForTypesOfCamping(){
    		TypesOfCamping backpack = TypesOfCamping.BACKPACK;
    		TypesOfCamping tent = TypesOfCamping.TENT_NON_ELECTRIC;
    		TypesOfCamping tentElectric = TypesOfCamping.TENT_ELECTRIC;
    		TypesOfCamping rv = TypesOfCamping.RV_CAMPER;
    	}
    	/*
    	//statements that use the enumerations and one of their constants:
    	TypesOfCamping backpack = TypesOfCamping.BACKPACK;
    	TypesOfCamping tent = TypesOfCamping.TENT_NON_ELECTRIC;
    	TypesOfCamping tentElectric = TypesOfCamping.TENT_ELECTRIC;
    	TypesOfCamping rv = TypesOfCamping.RV_CAMPER;
    	*/
    }

    Why is the enum embedded in another class like that?
    It's not adding anything at all.
    Just have it as it's own class (an enum is a special sort of class) and file.

    And you can get rid of the method as well as it doesn't actually do anything and just confuses the situation.

    With Jim's post you should also be able to merge the camp cost into the enum, thus removing the getCampsiteFee method from the other class.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to use enhanced enumeration

    Quote Originally Posted by jim829 View Post
    To avoid problems with static contexts I simply invoke a start method from main. Quite often my static main entry
    point looks like this:
    Java Code:
    class SomeClass {
        public static void main(String [] args) {
            new SomeClass().start();//So is the start method intended for calling other static methods or what?
        }
    
        public void start() {
          // other stuff here (What other stuff?)
        }
        // more instance methods here (Why are you telling me to put instance methods here? I already told you 
        //that I can't call instance methods in a main method that's static.)
    }
    Quote Originally Posted by jim829 View Post
    Enums are more useful when you take advantage of the fact that they are essentially a special
    type of class. I use enums either with no embellishments (as simple, enforced constants)
    I tried it your way, but I'm still having problems. This time, please focus on the errors in the code comments:

    CampingEnum.java:
    Java Code:
    package InnerClass.test;
    import java.lang.*;
    import java.util.Scanner;
    
    import InnerClass.test.CampingEnum.TypesOfCamping;
    
    public class CampingEnum {
    	public enum TypesOfCamping{
    		BACKPACK(4.99,"Backpacker's checkpoint (fire pit included only)"),
    		TENT_NON_ELECTRIC(10.99,"picnic table, fire pit, and drinking water pump included"),
    		TENT_ELECTRIC(18.99,"electricity, picnic table, fire pit, and drinking water pump included"),
    		RV_CAMPER(24.99,"100-foot RV lot, electricity, picnic table, fire pit, and drinking water pump included");
    	
    		private double costPerNight;
    		private String campsiteDescription;
    	
    		private TypesOfCamping(double costPerNight, String campsiteDescription){
    			this.costPerNight = costPerNight;
    			this.campsiteDescription = campsiteDescription;
    		}
    		
    		public String getDescription(){
    			return campsiteDescription;
    		}
    		public double getCostPerNight(){
    			return costPerNight;
    		}
    	}//end of enum TypesOfCamping constructor
    	
    	@Override
    	public String toString(){
    		String s = "";
    		if(this.TypesOfCamping.ordinal() == 0){//error: TypesOfCamping cannot be resolved or is not a field
    			s = getDescription() + "Overridding Backpacker's campsite description.";//error: The 
    			//method getDescription() is undefined for the type CampingEnum
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 1){
    			s = getDescription() + "Overridding non-electric tent campsite description.";
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 2){
    			s = getDescription() + "Overridding electric tent campsite description.";
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 3){
    			s = getDescription() + "Overridding RV campsite description.";
    			System.out.println(s);
    		}else{
    			System.out.println("Invalid campsite type. No description to override.");
    		}
    		return s;
    	}
    	
    	//Make sure the enumerations are working correctly:
    	public static void printOrdinalValues(){
    		System.out.println("Enum ordinal value for " + TypesOfCamping.BACKPACK.name() 
    		+ " is " + TypesOfCamping.BACKPACK.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_NON_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_NON_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.RV_CAMPER.name() 
    		+ " is " + TypesOfCamping.RV_CAMPER.ordinal());
    	}
    	
    	public static void main(String args[]){
    		new CampingEnum().start();//error: The method start() is undefined for the type CampingEnum
    		printOrdinalValues();
    		double nightlyCampingFee = 0.0;
    		String s = "";
    		
    		Scanner typeOfCampsite = new Scanner(System.in);
    		int type = typeOfCampsite.nextInt();
    		System.out.println("The continue brought the user back here successfully.");
    		while((type != 0) || (type != 1) || (type != 2) || (type != 3)){	
    			System.out.println("Please select the type number of the campsite you are looking for:\n"
    					+ "0: Backpack camping\n"
    					+ "1: Tent without electricity\n"
    					+ "2: Tent with electricity\n"
    					+ "3: RV parking space");
    			if(type == 0){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 0
    				type = TypesOfCamping.BACKPACK.ordinal();
    				nightlyCampingFee = CampsiteFees.getCampsiteFee(TypesOfCamping.BACKPACK);
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();//error: Cannot make a static reference to the non-static method toString()
    				//from the type CampsiteFees
    				System.out.println("You selected " + TypesOfCamping.BACKPACK.name());
    				System.out.println("It includes " + TypesOfCamping.BACKPACK.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.BACKPACK.getCostPerNight() + " per night.");
    			}else if(type == 1){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 1
    				type = TypesOfCamping.TENT_NON_ELECTRIC.ordinal();
    				nightlyCampingFee = CampsiteFees.getCampsiteFee(TypesOfCamping.TENT_NON_ELECTRIC);
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.TENT_NON_ELECTRIC.name());
    				System.out.println("It includes " + TypesOfCamping.TENT_NON_ELECTRIC.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.TENT_NON_ELECTRIC.getCostPerNight() + " per night.");
    			}else if(type == 2){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 2
    				type = TypesOfCamping.TENT_ELECTRIC.ordinal());
    				nightlyCampingFee = CampsiteFees.getCampsiteFee(TypesOfCamping.TENT_ELECTRIC);
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.TENT_ELECTRIC.name());
    				System.out.println("It includes " + TypesOfCamping.TENT_ELECTRIC.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.TENT_ELECTRIC.getCostPerNight() + " per night.");
    			}else if(type == 3){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 3
    				type = TypesOfCamping.RV_CAMPER.ordinal();
    				nightlyCampingFee = CampsiteFees.getCampsiteFee(TypesOfCamping.RV_CAMPER);
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.RV_CAMPER.name());
    				System.out.println("It includes " + TypesOfCamping.RV_CAMPER.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.RV_CAMPER.getCostPerNight() + " per night.");
    			}else{
    				System.out.println("Invalid campsite type number. Please enter 0, 1, 2, or 3 and "
    						+ "try again.");
    				continue;
    			}
    		}//end of while loop				
    	}//end of main method
    }

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    Seriously.
    Move the enum into its own file.

    And your other class does not have a start() method.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to use enhanced enumeration

    Quote Originally Posted by Tolls View Post
    Seriously. Move the enum into its own file.
    I assume you mean like this:

    CampingEnum.java:
    Java Code:
    package InnerClass.test;
    import InnerClass.test.CampingEnum.TypesOfCamping;
    
    public class CampingEnum {
    	public enum TypesOfCamping{
    		BACKPACK(4.99,"Backpacker's checkpoint (fire pit included only)"),
    		TENT_NON_ELECTRIC(10.99,"picnic table, fire pit, and drinking water pump included"),
    		TENT_ELECTRIC(18.99,"electricity, picnic table, fire pit, and drinking water pump included"),
    		RV_CAMPER(24.99,"100-foot RV lot, electricity, picnic table, fire pit, and drinking water pump included");
    	
    		private double costPerNight;
    		private String campsiteDescription;
    	
    		private TypesOfCamping(double costPerNight, String campsiteDescription){
    			this.costPerNight = costPerNight;
    			this.campsiteDescription = campsiteDescription;
    		}
    		
    		public String getDescription(){
    			return campsiteDescription;
    		}
    		public double getCostPerNight(){
    			return costPerNight;
    		}
    	}//end of enum definition
    CampsiteFees.java:
    Java Code:
    //How to create and use my own enumerations
    package InnerClass.test;
    import java.lang.*;
    import java.util.Scanner;
    
    import InnerClass.test.CampingEnum.TypesOfCamping;
    
    import static InnerClass.test.CampingEnum.*;
    public class CampsiteFees {	
    	@Override
    	public String toString(){
    		String s = "";
    		if(this.TypesOfCamping.ordinal() == 0){//error: TypesOfCamping cannot be resolved or is not a field
    			s = getDescription() + "Overridding Backpacker's campsite description.";//error: The 
    			//method getDescription() is undefined for the type CampingEnum
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 1){
    			s = getDescription() + "Overridding non-electric tent campsite description.";
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 2){
    			s = getDescription() + "Overridding electric tent campsite description.";
    			System.out.println(s);
    		}else if(this.TypesOfCamping.ordinal() == 3){
    			s = getDescription() + "Overridding RV campsite description.";
    			System.out.println(s);
    		}else{
    			System.out.println("Invalid campsite type. No description to override.");
    		}
    		return s;
    	}
    	
    	//Make sure the enumerations are working correctly:
    	public static void printOrdinalValues(){
    		System.out.println("Enum ordinal value for " + TypesOfCamping.BACKPACK.name() 
    		+ " is " + TypesOfCamping.BACKPACK.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_NON_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_NON_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.RV_CAMPER.name() 
    		+ " is " + TypesOfCamping.RV_CAMPER.ordinal());
    	}
    	
    	public static void main(String args[]){
    		new CampingEnum().start();//error: The method start() is undefined for the type CampingEnum
    		printOrdinalValues();
    		double nightlyCampingFee = 0.0;
    		String s = "";
    		
    		Scanner typeOfCampsite = new Scanner(System.in);
    		int type = typeOfCampsite.nextInt();
    		System.out.println("The continue brought the user back here successfully.");
    		while((type != 0) || (type != 1) || (type != 2) || (type != 3)){	
    			System.out.println("Please select the type number of the campsite you are looking for:\n"
    					+ "0: Backpack camping\n"
    					+ "1: Tent without electricity\n"
    					+ "2: Tent with electricity\n"
    					+ "3: RV parking space");
    			if(type == 0){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 0
    				type = TypesOfCamping.BACKPACK.ordinal();
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();//error: Cannot make a static reference to the non-static method toString()
    				//from the type CampsiteFees
    				System.out.println("You selected " + TypesOfCamping.BACKPACK.name());
    				System.out.println("It includes " + TypesOfCamping.BACKPACK.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.BACKPACK.getCostPerNight() + " per night.");
    			}else if(type == 1){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 1
    				type = TypesOfCamping.TENT_NON_ELECTRIC.ordinal();
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.TENT_NON_ELECTRIC.name());
    				System.out.println("It includes " + TypesOfCamping.TENT_NON_ELECTRIC.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.TENT_NON_ELECTRIC.getCostPerNight() + " per night.");
    			}else if(type == 2){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 2
    				type = TypesOfCamping.TENT_ELECTRIC.ordinal();
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.TENT_ELECTRIC.name());
    				System.out.println("It includes " + TypesOfCamping.TENT_ELECTRIC.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.TENT_ELECTRIC.getCostPerNight() + " per night.");
    			}else if(type == 3){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 3
    				type = TypesOfCamping.RV_CAMPER.ordinal();
    				System.out.println("The static method gave us: $" + nightlyCampingFee);
    				s = toString();
    				System.out.println("You selected " + TypesOfCamping.RV_CAMPER.name());
    				System.out.println("It includes " + TypesOfCamping.RV_CAMPER.getDescription());
    				System.out.println("This type of campsite costs $" 
    				+ TypesOfCamping.RV_CAMPER.getCostPerNight() + " per night.");
    			}else{
    				System.out.println("Invalid campsite type number. Please enter 0, 1, 2, or 3 and "
    						+ "try again.");
    				continue;
    			}
    		}//end of while loop				
    	}//end of main method		
    }
    Quote Originally Posted by Tolls View Post
    And your other class does not have a start() method.
    Okay fine, but then how do you call non-static methods in a static main method?

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    No.

    TypesOfCamping.java
    Java Code:
    package InnerClass.test;
    public enum TypesOfCamping{
            BACKPACK(4.99,"Backpacker's checkpoint (fire pit included only)"),
            TENT_NON_ELECTRIC(10.99,"picnic table, fire pit, and drinking water pump included"),
            TENT_ELECTRIC(18.99,"electricity, picnic table, fire pit, and drinking water pump included"),
            RV_CAMPER(24.99,"100-foot RV lot, electricity, picnic table, fire pit, and drinking water pump included");
         
            private double costPerNight;
            private String campsiteDescription;
         
            private TypesOfCamping(double costPerNight, String campsiteDescription){
                this.costPerNight = costPerNight;
                this.campsiteDescription = campsiteDescription;
            }
             
            public String getDescription(){
                return campsiteDescription;
            }
            public double getCostPerNight(){
                return costPerNight;
            }
        }
    This will cure some of your issues.

    Now, if you want a method to list all the enum ordinals then stick it in this class as a static method.

    You can also add a (non-static) toString() to @Override the base toString from Object so it can print out the details of a particular enum:

    Java Code:
    @Override
    public String toString() {
        return name() + ": " + campsiteDescription + " (" + costPerNight + ")";
    }
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    Okay fine, but then how do you call non-static methods in a static main method?
    If you look at Jim's code he creates an instance of the class:

    Java Code:
    class SomeClass {
        public static void main(String [] args) {
            new SomeClass().start();
        }
     
        public void start() {
          // other stuff here
        }
        // more instance methods here
    }
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: How to use enhanced enumeration

    This time, please focus on the errors in the code comments:
    Well, your errors are basic and unrelated to enum usage. So I am going to give you some advice.

    1. Understand and practice using static vs instance fields and methods. Think of it
    this way, if a class has a static method and wants to access an instance field. Which instance
    would it choose? There could be very many. That is why the method or field must be qualified
    with an instance reference. Instance methods don't have this problem when accessing static members,
    since the static members are the same for all instances.

    2. Review the advantages of methods. You can pass an enum to a method which can then
    print the enum characteristics. No need to duplicate code. It is no different than passing
    an instance of a class to a method and print the various fields. See lines 60-68 and other
    similar blocks of code.

    3. Do not use ordinal() (probably should have told you this earlier). There may be uses but the
    way you are using it is fragile. If you change the order of your enum constants, your code will break.
    In the code I will show you one way to do it. You could also have passed a value via the constructor.
    Since ordinal() is final you can't override it so a new method would be required. Note: No need
    to change it for this exercise as long as you are aware of the problems. But in the future, I would
    avoid it.

    4. Each enum constant may have its own version of a method (including toString()). This
    is what Toll's was referring too. It is not obvious and requires reading about enum capabilities. Perhaps
    you had not read that part in your book. The syntax is a bit foreign so I included an example
    along with the ordinal() replacement.

    Java Code:
    enum Fruit {
       // Price per lb. and description
       GRAPES(2.99, "Red, Red Seedless, Green Seedless") {
         
          @Override
          public String toString() {
             return "This is the Grapes toString: " + getDescription();
          }
          public int idValue() {
             return 0;
          }
       },
       APPLES(1.99, "Rome, Golden Delicious, and Gala") {
          
          @Override
          public String toString() {
             return "This is the Apples toString: " + getDescription();
          }
          public int idValue() {
             return 1;
          }
       };
    
       private double price;
       private String description;
    
       private Fruit(double price, String description) {
          this.price = price;
          this.description = description;
       }
    
       // forces each enum constant to provide a method body.
       public abstract int idValue();
      
       public double getFee() {
          return price;
       }
    
       public String getDescription() {
          return description;
       }
    
    }
    
    public class EnumDemo {
       public static void main(String args[]) {
          for (Fruit f : Fruit.values()) {
             System.out.println(f.idValue());
             System.out.println(f);
          }
       }
    }

    Regards,
    Jim
    Last edited by jim829; 08-24-2016 at 05:00 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to use enhanced enumeration

    Quote Originally Posted by jim829 View Post
    Do not use ordinal() (probably should have told you this earlier). There may be uses but the
    way you are using it is fragile. If you change the order of your enum constants, your code will break.
    That doesn't really scare me. In addition, I've attempted check both the idValues and actual ordinal() values in the nonStaticPrint() method defined in TypesOfCamping.java on lines 41 to 51. The part I'm having trouble with is figuring out how to call that instance method from the main method in CampsiteFees.java

    Quote Originally Posted by jim829 View Post
    In the code I will show you one way to do it. You could also have passed a value via the constructor.
    Since ordinal() is final you can't override it so a new method would be required.
    I thought that overriding the toString() method simply meant that we are adding the name() or ordinal() values to some string of text. Consequently, we aren't replacing or overriding the finalized name() or ordinal() values themselves. Is that accurate?

    Quote Originally Posted by jim829 View Post
    Each enum constant may have its own version of a method (including toString()). This
    is what Toll's was referring too. It is not obvious and requires reading about enum capabilities. Perhaps
    you had not read that part in your book. The syntax is a bit foreign so I included an example
    along with the ordinal() replacement.
    So there's no way of getting around having to hardcode a toString() method for each individual enum constant? That would be disappointing

    With the errors and questions in the code comments, here is the newest version of my code:

    TypesOfCamping.java:
    Java Code:
    package InnerClass.test;
    
    public enum TypesOfCamping{
    	BACKPACK(0,4.99,"Backpacker's checkpoint (fire pit included only)"),
    	TENT_NON_ELECTRIC(1,10.99,"picnic table, fire pit, and drinking water pump included"),
    	TENT_ELECTRIC(2,18.99,"electricity, picnic table, fire pit, and drinking water pump included"),
    	RV_CAMPER(3,24.99,"100-foot RV lot, electricity, picnic table, fire pit, and drinking water pump included");
    
    	private double costPerNight;
    	private String campsiteDescription;
    	private int idValue;
    
    	private TypesOfCamping(int idValue, double costPerNight, String campsiteDescription){
    		this.costPerNight = costPerNight;
    		this.campsiteDescription = campsiteDescription;
    	}
    	
    	public int getIdValue(){
    		return idValue;
    	}
    	public String getDescription(){
    		return campsiteDescription;
    	}
    	public double getCostPerNight(){
    		return costPerNight;
    	}	
    	
    	//Make sure the enumerations are working correctly:
    	public static void printOrdinalValues(){
    		System.out.println("Lets print the ordinal enumeration values using a static method:");
    		System.out.println("Enum ordinal value for " + TypesOfCamping.BACKPACK.name() 
    		+ " is " + TypesOfCamping.BACKPACK.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_NON_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_NON_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.TENT_ELECTRIC.name() 
    		+ " is " + TypesOfCamping.TENT_ELECTRIC.ordinal());
    		System.out.println("Enum ordinal value for " + TypesOfCamping.RV_CAMPER.name() 
    		+ " is " + TypesOfCamping.RV_CAMPER.ordinal());
    	}
    	
    	public void nonStaticPrint(){
    		System.out.println("Lets print the ordinal enumeration values again, this time by using "
    				+ "a non-static method:");
    		for(TypesOfCamping camp : TypesOfCamping.values()) {
    			 System.out.println("For the " + camp.name() + "type of campsite,");
    	         System.out.println("both the id value, " + camp.idValue);
    	         System.out.println("and the ordinal value " + camp.ordinal());
    	         System.out.println("should be the same.");
    	         System.out.println();
    	      }
    	}
    	
    	@Override
    	public String toString() {
    	    String campsiteInfo = "You have selected a " + name() + " campsite.\n" 
    	    		+ "It includes " + campsiteDescription + ".\n" 
    	    		+ "It costs $" + costPerNight + "per night.\n";
    	    return campsiteInfo;
    	}
    }//end of enum definition
    CampingFees.java:
    Java Code:
    package InnerClass.test;
    import java.lang.*;
    import java.util.Scanner;
    import InnerClass.test.TypesOfCamping;
    import static InnerClass.test.TypesOfCamping.*;
    
    public class CampsiteFees {	
    	public static void main(String args[]){
    		TypesOfCamping.printOrdinalValues();//print ordinal values using static method
    		
    		TypesOfCamping camp;//It wouldn't let me instantiate "TypesOfCamping camp = new TypesOfCamping();"
    		camp.nonStaticPrint();		
    				
    		//while((type != 0) || (type != 1) || (type != 2) || (type != 3)){
    			//System.out.println("The while loop is now starting once again.");
    			System.out.println("Please select the type number of the campsite you are looking for:\n"
    					+ "0: Backpack camping\n"
    					+ "1: Tent without electricity\n"
    					+ "2: Tent with electricity\n"
    					+ "3: RV parking space\n");
    			String s = "";
    			Scanner typeOfCampsite = new Scanner(System.in);
    			int type = typeOfCampsite.nextInt();
    			if(type == 0){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 0
    				type = TypesOfCamping.BACKPACK.ordinal();
    				s = TypesOfCamping.BACKPACK.toString(campsiteInfo);//error: campsiteInfo cannot be resolved to a variable
    			}else if(type == 1){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 1
    				type = TypesOfCamping.TENT_NON_ELECTRIC.ordinal();				
    				s = TypesOfCamping.TENT_NON_ELECTRIC.toString();
    			}else if(type == 2){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 2
    				type = TypesOfCamping.TENT_ELECTRIC.ordinal();				
    				s = TypesOfCamping.TENT_ELECTRIC.toString();
    			}else if(type == 3){//if user-entered type number == TypesOfCamping enumeration ordinal() 
    				//constant position 3
    				type = TypesOfCamping.RV_CAMPER.ordinal();				
    				s = TypesOfCamping.RV_CAMPER.toString();
    			}else{
    				System.out.println("Invalid campsite type number. Please enter 0, 1, 2, or 3 and "
    						+ "try again.");
    				//continue;//should take us back to the beginning of the while loop
    			}
    		//}//end of while loop				
    	}//end of main method		
    }
    One other thing. On line 13 of CampsiteFees.java, I get the error "The local variable camp may not have been initialized" when I delete the campsiteInfo argument on line 28. Any idea what causes that strange behavior?

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: How to use enhanced enumeration

    SOme comments:
    Java Code:
        public void nonStaticPrint(){
            System.out.println("Lets print the ordinal enumeration values again, this time by using "
                    + "a non-static method:");
            for(TypesOfCamping camp : TypesOfCamping.values()) {
                 System.out.println("For the " + camp.name() + "type of campsite,");
                 System.out.println("both the id value, " + camp.idValue);
                 System.out.println("and the ordinal value " + camp.ordinal());
                 System.out.println("should be the same.");
                 System.out.println();
              }
        }
    You wouldn't do this in real life.
    An instance method (which this is) should not be dealing with iterating over all instances of the class it is part of.
    It should only have responsibility over itself and its data.

    So this should not be looping and should just print out the name, id and ordinal for the instance it is called on.

    "It wouldn't let me instantiate "TypesOfCamping camp = new TypesOfCamping();"

    Yes, it's an enum. An enum has a set of predefined instances and you cannot instantiate any more at runtime.

    "error: campsiteInfo cannot be resolved..." (this is a reason not to stick your questions inlined in the code, it cuts off text)

    You don't have a campsiteInfo variable. Even if you did, toString doesn't take any parameters.

    Indeed, this whole section (finding a TypesOfCamping instance based on an entered id) should be done as a static method on the enum. Code outside the enum should not care that id 'x' maps to enum 'Y'.

    Oh, and TypesOfCamping should be TypeOfCamping.
    Each instance is a single TypeOfCamping, not a collection.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: How to use enhanced enumeration

    So there's no way of getting around having to hardcode a toString() method for each individual enum constant? That would be disappointing
    I was just giving you an example. You don't need to override anything. If you simply return a String within the enum which is composed of the
    ordinal and the name, then it will return the appropriate string depending on which enum constant you print. But I recommend you experiment with an
    isolated example rather than work with your existing code.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. StringArray Enumeration
    By loopsnhoops in forum New To Java
    Replies: 1
    Last Post: 06-01-2011, 06:30 PM
  2. nxn 0-1 array enumeration
    By hollygrove in forum Advanced Java
    Replies: 3
    Last Post: 10-16-2009, 09:33 AM
  3. Enumeration
    By kishan in forum Advanced Java
    Replies: 3
    Last Post: 06-19-2009, 12:27 AM
  4. Using the built-in enumeration methods
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 07:35 PM
  5. Declaring Enumeration
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-04-2007, 05:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •