Results 1 to 6 of 6
  1. #1
    gcampton Guest

    Question [solved] how do I Parse Enumerated types?

    In the book I am reading it says that for variables that are always similar eg days of week, cloud types, etc you should always use enumerated types.

    But the examples in the book really only show how to declare them, there's no examples how to use them.

    I need to use them as a requirement of my assignment for uni, but I'm not quite sure how I am supposed to implement this.

    The assignment is a Menu text based system for a business Second Hand Car Sales, we are required to create a menu system for admin to log into the system via user-name/password which is then written to a log file time of logon, and user-name. The menu items include add a vehicle, delete a vehicle, show the log, sort the vehicles, search the vehicles etc.
    I have done this before with simple arrays, but with the addition of enumerated types and extremely long params to my classes adding the file to the array is become a bit of a challenge.

    So far I have written my main which simply calls my driver until the user-input is equal to quit.

    I have the driver running the menu system and checks if the user is already logged in, if not then will create an object of the 3rd file which deals with I/O opens the security file validates, and then logs the user into the system.

    If the user is logged in then it prints the main menu to the screen. And will accept menu choices print the log file, and the list vehicles menu, which simply lists the vehicles using String.split(":");

    So what I am stuck on is A: reading my data File into an object array, and how to deal with the enumerated types. The last project I did like this was a candy store but only have very easy params type name and cost, there was only 4 types candy, icecream, cookies, topping, so I had a simple if (was using string tokenizer at the time, it is now depreciated...
    Java Code:
    public final static int CANDY=0;
    public final static int COOKIE=1;
    public final static int ICECREAM=2;
    public final static int TOPPING=3;
    
    public void addFile2Array()
    {
        st=new StringTokenizer(inStr,":");
        itemName=st.nextToken();
        itemType=st.nextToken();
        itemCose=st.nextToken();
    
        if (itemName.equals("CANDY"))
        {
            if(inventoryArray.length>= candyCount)
            {
                // add a new element by calling a method addElement(array[] d);
            }
            inventoryArray[CANDY][candyCount++] = new CandyItem(itemType,Integer.parseInt(itemCost));
        {
        else if .... cookie etc
    So simple enough, however my vehicle abstract class contains 2 children.
    Car and Truck. both params = 9 but slightly different.
    Car has:
    (String registration, Enum type, String make, String model, Enum color, double price, int odometer, int year, Enum condition)

    type is Sedan, Hatch, Coupe, Wagon etc.
    make is manufacturer, model is model, color will be typical primary & secondary colors, metallics, shades, and a few favs like PINK!!!
    price is price, odometer, year is the year it was made, and condition will be 5 or so enums, Excellent, good, average, poor, scrap-metal.

    Truck params is slightly different it does not have type, so trucks can't be sedans hatches etc. but it has an extra param called load, load is the load limit (amount of weight the truck can hold).

    if anyone has any links to Thorough enum usage and or explanation that would be very helpful as well, as far as I can tell Enums act like objects, but I don't understand why.... why can't they just be Strings of a enumerated type.( makes more sense to me, but I didn't write the jvm :P )

    or if anyone knows how I should parse the string to enum to create the object that would be great as well. :)

    Also with declaring the enums I'm not quite sure how I use them in the params of the class. do I just make them static and say
    public static enum vType{ "SEDAN","HATCH","etc" }

    public class Car extends Vehicle {
    public Car(vType vehicleType) ? {
    }
    }
    Thanks in advance :)
    Last edited by gcampton; 10-11-2009 at 06:48 AM.

  2. #2
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Enums are like classes, but unlike classes, enums have a limited number of instances, defined at compile-time. Check out Enum Types (in the Java tutorials) for more details.

    Now, as for "parse the string to enum to create the object", it depends on your needs. First, to clarify, you cannot create a new enum object. Rather, what you want is to return a specific instance of the enum.

    If the string is the name of a variable of the given enum, the valueOf(String) method is what you want.

    Java Code:
    public class ColorTest
    {
    	public enum Color
    	{
    		RED, GREEN, BLUE;
    	}
    
    	/**
    	 * Main function
    	 * 
    	 * @param args
    	 *            (not used)
    	 */
    	public static void main(String[] args)
    	{
    		String color = "RED";
    
    		// returns the Color instance 
    		// with the specified variable name (case-sensitive)
    		Color myColor = Color.valueOf(color);
    
    		output(myColor);		
    	}
    	
    	public static void output(Color color)
    	{
    		//calls the toString method in the Color enum
    		//(by default, it returns the variable's name, color.name())
    		System.out.println("The color you chose is " + color);
    	}
    }
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  3. #3
    gcampton Guest

    Default

    Excellent, now a block like that in the book would have made much more sense :D

    Thanks mate.

  4. #4
    gcampton Guest

    Default

    Also because they are constants it would be fine to have them as publics and be able to access them everywhere in the program say from one file, maybe my Vehicle super-class. Because they seem to be unlike other variables which in most cases are private, or hidden in method scope. Is this right?

  5. #5
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Quote Originally Posted by gcampton View Post
    Also because they are constants it would be fine to have them as publics and be able to access them everywhere in the program say from one file, maybe my Vehicle super-class. Because they seem to be unlike other variables which in most cases are private, or hidden in method scope. Is this right?
    You're right, enums aren't variables like you're thinking. You're thinking of member variables, for example, a Car could have a Color enum as a field, and you would usually declare it as private. However, Color could apply to a Car, a Shape, or anything, and declaring is public is fine (but you can declare it as protected, default, or private).

    A Color enum value is an instance of a Color object. Just like your could have several Car objects, you can have several Colors. However, unlike a Car class, an enum only has a specific number of instances.


    As per your question, enums are not "constants", but are static final values. This means that although you can't assign a new value, for example Color.RED = Color.GREEN, you can change the data within. Also, enums are unique references and you can't create new ones, so you can use "==" to compare them.

    Java Code:
    /**
     * Test class to demonstrate enum functionality
     */
    public class ColorTest
    {
    	public enum Color
    	{
    		RED, GREEN, BLUE;
    
    		private String value;
    
    		private Color()
    		{
    			value = name();
    		}
    
    		public void setValue(String value)
    		{
    			this.value = value;
    		}
    
    		public String getValue()
    		{
    			return value;
    		}
    	}
    
    	/**
    	 * Main function
    	 * 
    	 * @param args
    	 *            (not used)
    	 */
    	public static void main(String[] args)
    	{
    		String color = "RED";
    
    		// returns the Color instance
    		// with the specified variable name (case-sensitive)
    		Color myColor = Color.valueOf(color);
    
    		// Color.RED = Color.GREEN; // compile-time error
    
    		// outputs "RED"
    		System.out.println("old value: " + myColor);
    
    		// changes the value in Color.RED
    		myColor.setValue("set RED value");
    
    		// outputs "new value"
    		System.out.println(myColor.getValue());
    
    		// comparable using "=="
    		if (myColor == Color.GREEN)
    			System.out.println("Green (if)");
    		else if (myColor == Color.BLUE)
    			System.out.println("Blue (if)");
    		else if (myColor == Color.RED)
    			System.out.println("Red (if)");
    
    		// usable in switch
    		switch (myColor) {
    		case BLUE:
    			System.out.println("Blue (switch)");
    			break;
    		case GREEN:
    			System.out.println("Green (switch)");
    			break;
    		case RED:
    			System.out.println("Red (switch)");
    			break;
    		default:
    			throw new IllegalArgumentException(
    					"The Color doesn't have a case statement");
    		}
    
    		output(myColor);
    	}
    
    	public static void output(Color color)
    	{
    		// calls the toString method in the Color enum
    		// (by default, it returns the variable's name, color.name())
    		System.out.println("The color you chose is " + color);
    	}
    }
    Last edited by CodesAway; 10-11-2009 at 11:31 PM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  6. #6
    gcampton Guest

Similar Threads

  1. Problem using enumerated types
    By Stryker4526 in forum New To Java
    Replies: 3
    Last Post: 10-10-2009, 03:57 AM
  2. How to parse a .db file ?
    By aminov in forum JDBC
    Replies: 0
    Last Post: 08-06-2009, 04:11 PM
  3. SAX Parse
    By bluefloyd8 in forum New To Java
    Replies: 1
    Last Post: 01-25-2008, 03:57 PM
  4. how to parse an xml file
    By oregon in forum XML
    Replies: 3
    Last Post: 08-01-2007, 04:53 PM
  5. How to parse in html
    By paty in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 12:29 AM

Posting Permissions

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