Enum ToString()

Can someone explain these program.
1. In IsFlagDefined method  when i print e.ToString() it prints different outputs on each iteration.I am not able to understand how enum.tostring() works for this program.Please help me on these.
static bool IsFlagDefined (Enum e)
decimal d;
Console.WriteLine(e.ToString());
return !decimal.TryParse(e.ToString(), out d);
[Flags]
public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }
static void Main()
for (int i = 0; i <= 16; i++)
BorderSides side = (BorderSides)i;
IsFlagDefined (side);

<Enum>.ToString()
This Method only returns the readable name of the Value { Left, Right... }. To convert it to an double-value, you need to use following code:
public enum __en : int {
Bottom = 1,
Top = 2
__en e = __en.Top;
string s = e.ToString(); //s = "Top"
int n = (int)e; // n = 1
© 2015 Thomas Roskop
Germany // Deutschland

Similar Messages

  • Migrating from 2.1 GA to 2.2 beta

    I just switched from 2.1 GA to 2.2 beta b15.
    There are some issues I encountered. Can you help explain and/or solve them?
    1. Drag & Drop in my TreeView/ListView does not work anymore, throwing this exception:
    java.lang.IllegalArgumentException: DataFormat 'contactEntry' already exists.
    -      at javafx.scene.input.DataFormat.<init>(Unknown Source)
    when I call:
    DataFormat dataFormat = new DataFormat("contactEntry");
    in the onDragDetected method.
    This exception even terminates my whole application (COM Error).
    2. Most of my TextFields, which are bound bidirectional to a SimpleStringProperty throw a NullPointerException when I want to type in the textfield:
    java.lang.NullPointerException
    - com.sun.javafx.scene.control.behavior.TextInputControlBehavior.defaultKeyTyped(Unknown Source)
    -      at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction(Unknown Source)
    -      at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(Unknown Source)
    -      at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent(Unknown Source)
    -      at com.sun.javafx.scene.control.behavior.BehaviorBase$1.handle(Unknown Source)
    -      at com.sun.javafx.scene.control.behavior.BehaviorBase$1.handle(Unknown Source)
    3. I have a ComboBox with Enum.values() as DataSource and a cellFactory, which translates the Enum Value into a readable form. In 2.1 it displays correctly in both the ListView AND the button. In 2.2 the cellfactory only applies to the listview. The button displays the Enum.toString() value.
    I've read there was a change to allow a buttonCellFactory, but I would have expected, that, if the button doesn't have any, that it is the same as the normal cellFactory.
    I'd consider 1 & 2 critical bugs, can somebody help?

    Regarding 3), the behavior your describe (where cell factory no longer is used in the ComboBox button area) - this is the new behavior in 2.2. This change had considerable discussion on the openjfx-dev mailing list - if you aren't a member I highly recommend you consider joining. It's always great to get more feedback and have deeper discussions with other members of the community.
    When I made this change, I also updated the ComboBox JavaDoc to demonstrate one possible way of reinstating the old behavior. I have pasted it below for your reference.
    >
    As the ComboBox internally renders content with a ListView, API exists in the ComboBox class to allow for a custom cell factory to be set. For more information on cell factories, refer to the Cell and ListCell classes. It is important to note that if a cell factory is set on a ComboBox, cells will only be used in the ListView that shows when the ComboBox is clicked. If you also want to customize the rendering of the 'button' area of the ComboBox, you can set a custom ListCell instance in the button cell property. One way of doing this is with the following code (note the use of setButtonCell:
    Callback<ListView<String>, ListCell<String>> cellFactory = ...;
    ComboBox comboBox = new ComboBox();
    comboBox.setItems(items);
    comboBox.setButtonCell(cellFactory.call(null));
    comboBox.setCellFactory(cellFactory);
    >
    -- Jonathan

  • Wscompile + xmlbeans: class does not have a public accessible empty constru

    Hi
    I have some schema files from 3gpp.org and created java files with xmlbeans.
    Now I try to use them but wscompile complains:
    error: class provider.VersionType$Enum does not have a public accessible empty constructor
    that class is generated by xmlbeans and I can't modify it...
    The class is an innner class of an interface, and looks like this:
    * Enumeration value class for provider.VersionType.
    * These enum values can be used as follows:
    * <pre>
    * enum.toString(); // returns the string value of the enum
    * enum.intValue(); // returns an int value, useful for switches
    * // e.g., case Enum.INT_X_5_3_0
    * Enum.forString(s); // returns the enum value for a string
    * Enum.forInt(i); // returns the enum value for an int
    * </pre>
    * Enumeration objects are immutable singleton objects that
    * can be compared using == object equality. They have no
    * public constructor. See the constants defined within this
    * class for all the valid values.
    static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase
    * Returns the enum value for a string, or null if none.
    public static Enum forString(java.lang.String s)
    { return (Enum)table.forString(s); }
    * Returns the enum value corresponding to an int, or null if none.
    public static Enum forInt(int i)
    { return (Enum)table.forInt(i); }
    private Enum(java.lang.String s, int i)
    { super(s, i); }
    static final int INT_X_5_3_0 = 1;
    public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table =
    new org.apache.xmlbeans.StringEnumAbstractBase.Table
    new Enum[]
    new Enum("5.3.0", INT_X_5_3_0),
    private static final long serialVersionUID = 1L;
    private java.lang.Object readResolve() { return forInt(intValue()); }
    Can anyybody help me ?
    thanks
    Gabor

    Sorry, I think you are out-of-luck on this one. The JAXRPC spec mandates that an acceptable value type have a public empty constructor. The only work-around I can suggest is to write a wrapper bean around this one that has such a constructor and use that in you interface instead.

  • Adding toString() To an Enum Class

    I have a class like the following to create named constants (similar to enums in C++):
    public final class ColorConstant {   // final class!!
         private ColorConstant() {}         // private constructor!!
         public static final ColorConstant.RED = new HoldemConstant();
         public static final ColorConstant.BLUE = new HoldemConstant();
    //etc
    }Now, sometimes I have a handle to a ColorConstant object, and (for dubugging purposes) I want to know what it is. Problem is, If you just do "println(ColorConstant.RED)", for example, you get some garbage which is the string representatin of the object. Is there a way I can add a toString() method to the above class?
    Thanks for suggestions,
    John

    Now, sometimes I have a handle to a ColorConstant
    object, and (for dubugging purposes) I want to know
    what it is. Problem is, If you just do
    "println(ColorConstant.RED)", for example, you get
    some garbage which is the string representatin of the
    object. Is there a way I can add a toString() method
    to the above class?Of course. Just name the method:
    public String toString(), and have it return the appropriate string. If you want ColorConstant.RED to show "Red" for example though, you're going to have to add some state to your object, e.g. make the constructor take a String argument for the human-readable name ("Red"), and save that value as an object member.

  • Overriding toString for enum constants

    can anybody please point me to some sort of example or documentation for overriding toString for (individual) enum constants. the javadoc indicates that this should be possibly but it is not entirely clear to me how to do so.
    thanks in advance

    i had actually coded the following before posting, I just wanted to find alternatives or "best practice":
    protected static enum WorkflowState {
              REFERRAL_CREATED,
              QUOTE_CREATED,
              ORDER_APPROVED,
              ORDER_CREATED;
              public String toString() {
                   String str = null;
                   switch(this) {
                   case REFERRAL_CREATED:
                        return "Opened";
                   return str;
         }

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Sun's demo using enum doesn't seem to work for me

    I'm trying to run a demo from the Sun website, http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html, which includes the enum statement:
    public class SwitchEnumDemo {
        public enum Month { JANUARY, FEBRUARY, MARCH, APRIL,
                            MAY, JUNE, JULY, AUGUST, SEPTEMBER,
                            OCTOBER, NOVEMBER, DECEMBER }
        public static void main(String[] args) {
            Month month = Month.FEBRUARY;
            int year = 2000;
            int numDays = 0;
            switch (month) {
                case JANUARY:
                    // etc etc ...
            System.out.println("Number of Days = " + numDays);
    }However, copying-and-pasting the code into NetBeans, I get an error on the enum declaration stating: '';' expected. Warning: as of release 1.5, 'enum' is a keyword and may not be used as an identifier'. Well... I know that. Isn't that why I'm using it in the first place? Or am I confused?
    I'm using NeBeans 5.0 on Java 1.5.0_06.
    Any advice?
    Question 2: Once I get this thing working, is there any way I can get the month as an input from the user, without needing a long block stating
    if (input = "January") month = Month.JANUARY;
    else if (input = "Feburary") month = Month.FEBURARY;
      //etc etcThat is, can the string representation of a month be somehow kept within the enumerated Month itself, and that be used to check the user's input?
    Thanks for any advice!

    However, copying-and-pasting the code into NetBeans,
    I get an error on the enum declaration stating:
    '';' expected. Warning: as of release 1.5, 'enum'
    is a keyword and may not be used as an
    identifier'. Well... I know that. Isn't
    that why I'm using it in the first place? Or am I
    confused?
    I'm using NeBeans 5.0 on Java 1.5.0_06.I can't say for sure about that; it seems very odd. However, I do know that my IDE will warn me about those sorts of things if I configure my project for pre-1.5 operation. It allows me to say a project is for Java 1.4 even if I'm using a 1.5 JVM and will mention things like that so that forward compatibility can be considered. I don't suppose this could be the case with your situation?
    You might want to search for all instances of "enum" in your code, though, because it's hard to imagine the one instance which appears in the snippet you posted causing problems.
    Question 2: Once I get this thing working, is there
    any way I can get the month as an input from the
    user, without needing a long block stating{snip}
    Well, in this case you can just do
    for (Month m : Month.values())
        if (m.toString().equalsIgnoreCase(input))
            month = m;
            break;
    }or you can build a Map<String,Month> if you're looking for case-sensitive comparison.
    In general, however, you can put pretty much anything into an enum:
    public enum SomeEnum
        A(0),
        B(0),
        C(1),
        D(0),
        E(2);
        private int value;
        SomeEnum(int value)
            this.value = value;
        public int getValue()
            return value;
    // the following is perfectly legal
    SomeEnum e = methodThatReturnsSomeEnum();
    System.out.println(e.getValue());and you could use that to put some form of identifier in the enumeration object. I have a class around here somewhere which uses an enum to enumerate the operators in an expression parser; the Operator enum constructor accepts an int specifying the operator precedence.

  • What's the deal with enums?

    Hello,
    I'm trying to familiarise myself with the new Java features that project Tiger (Java 1.5) will introduce. I come from a C++ programming background. I very briefly studied enums whilst I learned C++ and never used them in my programs, so I was, quite frankly, relieved when I learned that Java didn't support them.
    But now it does.
    I'm wondering, from a software design and engineering perspective, what benefit enums will add to the Java language and software engineering in general. I have read some pleas and arguments for enums. As I understand those arguments, proponents feel that minor ledgibility improvements to switch statements (which some OO programmers don't use on the basis that it weakens the object-orientedness through its goto-esque break statements) necessitate the addition of a whole other structure.
    Out of curiosity, wouldn't it be more advantageous for Sun to put their efforts into supporting constant strings in switches in addition to primitive data types if people are so concerned with clarity?
    I fail to understand what enums will do that constant string arrays or constant values cannot. I would like to think that Sun wouldn't add C++ features unless if there was a reason to do so, so I believe that there are good reasons to introduce this feature.
    Please help clarify this confusion.
    Thank you!

    Comments on the previous posting inline. Note: I'll go off on a few tangents, but try to always return to the issue of enums. The fact that I go off on tangents (related initially to an enum type example) should show that enums help eliminate numerous problems.
    Fair enough, but wouldn't this accomplish the same thing in
    a slightly wordier wayPretty much. But you still have the validation code in there yourself:
    currentDirection = ( direction > 0 && direction < 5 ? direction : 0 );People can still accidentally enter an invalid value, and it won't get caught by the compiler. So, I could call set(Compass.WEST) and hope/expect that is equivalent to set(Direction.LEFT). This will only occur if both Compass.WEST and Direction.LEFT are the same int value. If they are not, then we are in trouble. Worse, still if Compass.WEST and Direction.RIGHT are the same value, the code will compile, and run without any illegal value flagging, but our traveller will go off in the wrong direction.
    Error handling tangent: Given the implementation, the error handling is not performed in set, rather the illegal value is captured as a zero, which must be dealt with at a later time - say in a switch statement that calls get. This is not a good idea - it increases the "distance" between the error occuring (bad call to set) and the error being detected (if xInt != 0). The larger the distance, the harder debugging is. If you throw an exception in set the bug is immediately flagged. With enums, none of this should be necessary.
    Implementation tangent: set, get and currentDirection are static. This is not a good idea - it only allows one direction. If you have multiple travellers, each would have a Direction object, but (sticking with constants) UP, etc. would still be static.
    I keep the switch statement in my enum workaround, but I believe that
    the second reply suggested that enum could altogether eliminate the
    use for switch statements. How exactly would it do that?enum in its simplest form would not remove switch. However, using an extension of the type-safe enum idiom (i.e. the current Java approach to enums), you can embed direction specific logic in each of the "enum" members. If I understand the enum-spec correcly, this will also be possible with the Java 1.5 enum language facility.
    So, for an example, sticking with the domain: Consider a class Location, with x and y elements, and a Direction. The non-OO, non-enum approach would be as follows:
    class Location {
        int x,y;
        void move (final int direction) {
            switch (direction) {
                case UP:
                    --y;
                    break;
                case DOWN:
                    ++y;
                    break;
                case LEFT;
                    --x;
                    break;
                case RIGHT:
                    ++x;
                    break;
                default;
                    throw new RuntimeException("Invalid direction " + direction);
    class Direction {
        public static final int UP = 1;
        public static final int DOWN = 2;
        public static final int LEFT = 3;
        public static final int RIGHT = 4;
    }Note that I've deliberately been loose with my visibility. All logic is in Location, and Direction is dumb. If we go with a type safe-enum idiom, we get:
    class Location {
        int x,y;
        void move (final Direction direction) {
            if (direction == Direction.UP) {
                --y;
            } else if (direction == Direction.DOWN) {
                ++y;
            } else if (direction == Direction.LEFT) {
                --x;
            } else if (direction == Direction.RIGHT) {
                ++x;
            } else { // direction is null
                throw new NullPointerException("null direction");
    class Direction {
        public static final Direction UP = new Direction();
        public static final Direction DOWN = new Direction();
        public static final Direction LEFT = new Direction();
        public static final Direction RIGHT = new Direction();
        private Direction () {} // the ctor is private to limit instances
    }This code is a rewrite of the int approach, but is "type-safe". We've moved from switch to if as we can't switch on object references. Note: there is still error handling code, as you're not "null-safe" (I don't know what the Java 1.5 spec says about this)
    Little else has changed - the responsibilities are still the same. We can address this by going OO, which removes the if (formerly a switch) statement, but does couple the classes.
    class Location {
        int x,y;
        void move (final Direction direction) {
            direction.move(this);
    class Direction {
        private final int xOffset, yOffset;
        private Direction (final int xOffset, final int yOffset) {
            this.xOffset = xOffset;
            this.yOffset = yOffset;
        public static final Direction UP = new Direction(0,1);
        public static final Direction DOWN = new Direction(0,-1);
        public static final Direction LEFT = new Direction(-1,0);
        public static final Direction RIGHT = new Direction(1,0);
        void move(final Location location) {
            location.x += xOffset;
            location.y += yOffset;
    }This removes any conditional logic, embedding (constructor parameterised) logic within Direction. It also eliminates the "null-safe" check, as direction.move(this) will throw an NPE if a null is passed.
    Also, I've read some things saying that enum reduces 'boilerplate'
    code. What exactly does that and 'boilerplate' mean?The Direction class is an example of the type-safe enum approach currently used in Java. It has been enhanced with logic for movement. Even if I dropped this logic, there is still functionality worth adding to the Direction class - a toString method that returns one of "UP", "DOWN", etc (shown next); a way to serialize the object and retain reference equality - you have to write a readResolve method (not shown).
    class Direction {
        private final String name;
        private Direction (final String name) {
            this.name = name;
        public static final Direction UP = new Direction("UP");
        public static final Direction DOWN = new Direction("DOWN");
        public static final Direction LEFT = new Direction("LEFT");
        public static final Direction RIGHT = new Direction("RIGHT");
        public String toString() {
            return name;
    }Once you've written this code for one type-safe enum, you've written them for them all. You copy-cut-paste, and rename the class/elements. All this code is predictable. It is "boiler plate". Now, if you gave me a compiler that generated all this code for me, when I present it with
    enum Direction {UP, DOWN, LEFT, RIGHT}; then I've got something that reduces my boiler plate code to zip.... Enter the Java 1.5 compiler.

  • Java regular expressions using enum

    Hi,
    i have created an enum called MONTHS and would like to include it in a pattern. Can somebody give me a hint on how to do that? Should i do it manually (by creating a string like [Jan,Feb...]) or is there a better way?
    Thanks

    It works by iterating the months and getting a string: months= "Jan|Feb|..." and then appending it to the pattern string. For example:
        public static String getMonthsShortStringList()
            String sList="";
            for (MONTH_SHORT c: MONTH_SHORT.values())
                sList+=c.toString()+'|';
            String newS=sList.substring(0,sList.length()-1);       
            return newS;
        }//getMonthsShortStringList
    and  then...
    String months=DateConsts.getMonthsShortStringList(); //get a months disjunctive list
    Pattern pattern1=Pattern.compile("("+months+")");
    Matcher matcher1=pattern1.matcher((CharSequence)s);
    boolean found1=matcher1.find();Is there an alternative to this?

  • Class, interface, or enum expected error

    import java.awt.Graphics;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class InventoryFinal
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("CD", 10, 18, 12.00, "Jewel Case");
    nwProduct[1] = new ProductAdd("Blue Ray", 9, 20, 25.00, "HD");
    nwProduct[2] = new ProductAdd("Game", 8, 30, 40.00, "Game Case");
    nwProduct[3] = new ProductAdd("iPod", 7, 40, 50.00, "Box");
    nwProduct[4] = new ProductAdd("DVD", 6, 15, 15.00, "DVD Case");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JButton AddBtn = new JButton("Add"); // Add button
    final JButton DeleteBtn = new JButton("Delete"); // Delete button
    final JButton ModifyBtn = new JButton("Modify"); // Modify button
    final JButton SaveBtn = new JButton("Save"); // Save button
    final JButton SearchBtn = new JButton("Search"); // Search button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new MyJPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    buttonJPanel.add(AddBtn);
    buttonJPanel.add(DeleteBtn);
    buttonJPanel.add(ModifyBtn);
    buttonJPanel.add(SaveBtn);
    buttonJPanel.add(SearchBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("/nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("CD & DVD Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(600, 600); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screen location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    prevBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[4]+"\n");
    } // end prevBtn actionEvent
    }); // end prevBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[2]+"\n");
    } // end nextBtn actionEvent
    }); // end nextBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[3]+"\n");
    } // end lastBtn actionEvent
    }); // end lastBtn actionListener
    textArea.setText(nwProduct[4]+"n");// assign actionListener and actionEvent for each button
    AddBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end AddBtn actionEvent
    }); // end AddBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    DeleteBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end DeleteBtn actionEvent
    }); // end DeleteBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    ModifyBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end ModifyBtn actionEvent
    }); // end ModifyBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SaveBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SaveBtn actionEvent
    }); // end SaveBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SearchBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SearchBtn actionEvent
    }); // end SearchBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory4
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.10;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd
    class MyJPanel extends JPanel
    //private static Random generator = new Random();
    private ImageIcon picture; //image to be displayed
    // load image
    public MyJPanel()
    picture = new ImageIcon("mypicture.png"); // set icon
    } // end MyJPanel constructor
    // display imageIcon on panel
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    picture.paintIcon( this, g, 0, 0 ); // display icon
    } // end method paintComponent
    // return image dimensions
    //public Dimension getPreferredSize()
    // return new Dimension ( picture.getIconWidth(),
    //picture.getIconHeight() );
    } // end method getPreferredSize
    } // end class MyJPanel
    import java.io.File;
    import java.io.IOException;
    public class FileAccessDemo
    public static void main( String[] args ) throws IOException
    // declare variables
    String formatStr = "%s exists in %s? %b\n\n";
    // processing and output
    File file1 = new File( "studentScores.txt" ); // create a File object
    System.out.printf
    (formatStr, file1.getName(), file1.getAbsolutePath(), file1.exists());
    // processing and output
    File folder1 = new File( "c:/personnel/" ); // create a File object
    folder1.mkdir(); // make a directory
    File file2 = new File( "/personnel/faculty.txt" );
    file2.createNewFile(); // create a new file
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    // processing and output
    file2.delete(); // delete a file, but not the directory
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    } // end main
    } // end class
    I need help in resolving this error.
    Thanks

    That code isn't where your error is. Here's the errors I get compiling your code:
    H:\java>javac InventoryFinal.java
    InventoryFinal.java:78: ')' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                 ^
    InventoryFinal.java:78: ';' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                                                                   ^
    InventoryFinal.java:340: class, interface, or enum expected
    import java.io.File;
    ^
    InventoryFinal.java:341: class, interface, or enum expected
    import java.io.IOException;
    ^
    4 errorsThe last two errors are on your import statements, which can't be in the middle of a source file. The first two are on this line:
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n");Which certainly isn't a legal line of Java code. If you want to connect multiple Strings you need to use the "+" operator.

  • Enum from C/C++ in java?

    This is really a question for people who have used C/C++ and now use Java. Is there anything like the enum from the C/C++ language in Java? I would really like to use something like this, but as far as I can tell there is no way to create an enumeration of identifiers even by trying something like #define (any Java equivilent?). The best I can think of is create a class of 'properties' that have a bunch staticly defined variables.
    -- Deep_T

    Here's what I've done in the past for typseafe enums:
    public class Color{
    public static final Color RED=new Color();
    public static final Color GREEN=new Color();
    }There may be better ways to do it...I think the standard idiom is to have a private constructor that takes a string. This way a) you can't add new elements at runtime (though maybe in some cases you want to?) and b) you can have a meaningful toString() method.

  • Query on conversion between String to Enum type

    Hi All,
    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet letters before converting them back to their corresponding letters that belonged to enum type called definition.Alphabet, which is part of a global project used by other applications:
    package definition;
    public enum Alphabet
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S,
    T, U, V, W, X, Y, Z
    public StringBuffer uniqueRandomAlphabet()
    String currentAlphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    StringBuffer randomAlphabetSB = new StringBuffer();
    for (int numberOfAlphabet=26; numberOfAlphabet>0; numberOfAlphabet--)
    int character=(int)(Math.random()* numberOfAlphabet);
    String characterPicked = currentAlphabet.substring(character, character+1);
    // System.out.println(characterPicked);
    randomAlphabetSB.append(characterPicked);
    StringBuffer remainingAlphabet = new StringBuffer( currentAlphabet.length() );
    remainingAlphabet.setLength( currentAlphabet.length() );
    int current = 0;
    for (int currentAlphabetIndex = 0; currentAlphabetIndex < currentAlphabet.length(); currentAlphabetIndex++)
    char cur = currentAlphabet.charAt(currentAlphabetIndex);
    if (cur != characterPicked.charAt(0))
    remainingAlphabet.setCharAt( current++, cur );
    currentAlphabet = remainingAlphabet.toString();
    return randomAlphabetSB;
    // System.out.println(randomAlphabetSB);
    I got the following compilation error when trying to pass (Alphabet) StringBuffer[0] to a method that expects Alphabet.A type:
    inconvertible types
    required: definition.Alphabet
    found: char
    Any ideas on how to get around this. An alternative solution is to have a huge switch statement to assemble Alphabet type into an ArrayList<Alphabet>() but wondering whether there is a more shorter direct conversion path.
    I am using JDK1.6.0_17, Netbeans 6.7 on Windows XP.
    Thanks a lot,
    Jack

    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet lettersIf I understand well, you may be interested in method shuffle(...) in class java.util.Collections, which randomly reorders a list.
    before converting them back to their corresponding letters that belonged to enum type called definition.AlphabetIf I understand well, you may be interested in the built-in method Alphabet.valueOf(...) which will return the appropriate instance by name (you'll probably have no problem to build a valid String name from a lowercase char).

  • Passing any enum type to a method

    Consider I have created some enums:
    public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
    public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
    }I want to create a method that will accept any type of enum and display all values. So the call would look something like:
    showAll(Day);
    showAll(Month);I'm not sure what to pass to the method. My understanding of Generics is rudimentary at best, despite reading the tutorial several times now. Here is some uncompilable code that might illustrate:
    public void showAll(EnumType enumType)  // <--- not sure what to pass here
      Enum[] allValues = enumType.values();
      // then, loop over the allValues array and I can proceed from here
    }The actual code is needed is for displaying a list of checkboxes to the user where the input is the enum class, and the checkboxes are every enum value.

    brucechapman wrote:
    You could use this signature
    <T extends Enum<T>> void showall(Class<T> clazz); Then use reflection to invoke the values() method which you know is there because only Class objects for enums can be passed in.I'll be honest, that signature looks very strange to me. However, I tried it anyway and it worked even without reflection.
    public class PassingEnums
      public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
      public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
      public <T extends Enum<T>> void showAll(Class<T> clazz)
        T[] types = clazz.getEnumConstants();
        for (int i = 0; i < types.length; i++)
          System.out.println(types.toString());
    public static void main(String[] args)
    PassingEnums test = new PassingEnums();
    test.showAll(Day.class);
    System.out.println("---");
    test.showAll(Month.class);
    }Or were you thinking of something else?
    I guess I'll have to hit the tutorials again, since that signature looks foreign to me.
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Enum in JSF 1.2_06 - EnumConverter Bug

    Hi,
    I have a Enum as such :
    public enum ComponentType {
         AJAX_SUPPORT { public String toString(){ return "Ajax Support";} },
         INPUT_TEXT { public String toString(){ return "Input Text";}},
         OUTPUT_TEXT { public String toString(){ return "Output Text";}},
         PANEL_GRID { public String toString(){ return "Panel Grid";}},
         PANEL_GROUP { public String toString(){ return "Panel Group";}},
         PANEL { public String toString(){ return "Panel";}},
         SELECT_ONE_MENU { public String toString(){ return "Select One Menu";}},
         SELECT_ITEM { public String toString(){ return "Select Item";}}
    }when i put the Enum Values in datatable as such :
    <h:dataTable var="component" value="#{bean.allComponentTypes}">
                             <h:column>
                             </h:column>
    </h:dataTable>
    i get an exception as follows :
    javax.faces.convert.ConverterException: j_id1:j_id3:0:j_id8: 'Ajax Support' must be convertible to an enum from the enum, but no enum class provided.
         at javax.faces.convert.EnumConverter.getAsString(EnumConverter.java:195)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:447)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:286)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:154)
         at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:849)
         at org.ajax4jsf.renderkit.RendererBase.renderChild(RendererBase.java:286)
         at org.ajax4jsf.renderkit.RendererBase.renderChildren(RendererBase.java:262)
         at org.ajax4jsf.renderkit.html.AjaxOutputPanelRenderer.encodeChildren(AjaxOutputPanelRenderer.java:79)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:825)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:234)
         at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:312)
         at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:133)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:825)
         at org.ajax4jsf.renderkit.RendererBase.renderChild(RendererBase.java:282)
         at org.ajax4jsf.renderkit.RendererBase.renderChildren(RendererBase.java:262)
         at org.richfaces.renderkit.html.PanelRenderer.doEncodeChildren(PanelRenderer.java:199)
         at org.richfaces.renderkit.html.PanelRenderer.doEncodeChildren(PanelRenderer.java:194)
         at org.ajax4jsf.renderkit.RendererBase.encodeChildren(RendererBase.java:121)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:825)
         at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:234)
         at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:178)
         at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:126)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:825)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:936)
         at javax.faces.render.Renderer.encodeChildren(Renderer.java:148)
         at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:825)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:936)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:942)
         at com.sun.facelets.FaceletViewHandler.renderView(FaceletViewHandler.java:592)
         at org.ajax4jsf.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:108)
         at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:216)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:110)
         at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
         at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:989)
         at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:930)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:145)
         at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:141)
         at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:281)
         at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
         at com.bipt.tiva.interceptor.SessionFilter.doFilter(SessionFilter.java:45)
         at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
         at org.springframework.webflow.executor.jsf.FlowSystemCleanupFilter.doFilterInternal(FlowSystemCleanupFilter.java:40)
         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
         at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:87)
         at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:766)
         at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:674)
         at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:498)
         at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:464)
         at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:90)
         at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:744)
         at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1455)
         at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:113)
         at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
         at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:383)
         at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:102)
         at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
         at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
         at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
         at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136)
         at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:195)
         at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:743)
         at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:873)
         at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1469)This was not a problem when i used JSF 1.1 MyFaces
    So what gives ?
    Any knowledge on this would be helpful..

    Ok ok i got the answer
    if i change my Enum into :
    public enum ComponentType {
         AJAX_SUPPORT("Ajax Support"),
         INPUT_TEXT ("Input Text"),
         OUTPUT_TEXT ("Output Text"),     
         private String text;
           ComponentType(String text) {
           this.text = text; }
           public String toString(){
                return text;
    }then it works......
    but i still don't see a reason why the first approach should fail.

  • Bug Report: enum metadata containing 'true' and 'false' string values not displaying unless "goosed"

    I have metadata whose value is 'true' but the corresponding enum title is not being displayed. If I set it explicitly to 'true' it will be displayed even though the value is the same as it was.
    Likewise for 'false'.
    I do not have this problem with enums that have any other string values i.e. 'yes' and 'no' function properly, but 'true' and 'false' do not.
    Rob

    Due to better understanding on my part, and the fixes in Beta 2.2, the
    issues raised in this thread are put to rest.
    Abe White wrote:
    >
    We'll investigate further. Stay tuned...
    "David Ezzio" <[email protected]> wrote in message
    news:[email protected]..
    Abe,
    Actually, it doesn't make sense. The first iteration shows
    jdoPostLoad is called just prior to using the fields of Widget and Box.
    After the commit, the instances are not cleared. So far, so good.
    In the second iteration, we see that jdoPreClear is called, but
    jdoPostLoad is not called. Yet the values are there for use during the
    call to Widget.toString() and Box.toString() within the iteration. How
    did that happen?
    On the third iteration, now the value of name is null, but last we
    looked it was available in the second iteration. Other than that, I
    agree that the third iteration looks ok, since it is being cleared and
    loaded prior to use. But in the jdoPreClear, the values should be there
    since the values were used in the previous iteration and are not cleared
    at transaction commit due to retainValues == true.
    David
    Abe White wrote:
    David --
    I believe the behavior you are seeing to be correct. Section 5.6.1 of
    the
    JDO spec outlines the behavior of persistent-nontransactional instancesused
    with data store transactions. As you can see, persistentnon-transactional
    instances are cleared when they enter a transaction; thus the calls to
    jdoPreClear. When the default fetch group is loaded again (like whenyou
    access the name of the widget) a call to jdoPostLoad is made.
    You are seeing the name of one instance as 'null' in the third iterationof
    your loop because the instance has been cleared in the second iteration,and
    the jdoPreClear method is not modified by the enhancer (see section10.3).
    Make sense?

Maybe you are looking for

  • How to I see my Borders Desktop Books in ADE

    As per the rather difficult to locate directions on Border's site, I downloaded ADE to my laptop so I could transfer my newly purchased ebooks onto my reader.  However ADE does not see these books and I don't know how to make it see them.  I used to

  • I am actually using a free trial of photoshop cc and the contact sheet option does not work-?

    i am actually using a free trial of photoshop cc and the contact sheet option does not work...

  • New macbook, what to install?

    Hey guys, I am getting my macbook in seriously the next few hours from fedex...I was wondering, when I get it and power it up, what programs are essentials? like firefox/safari...other useful software brian

  • Cache engine with ASA

    Hi Can I use the Content Engine as a Reverse proxy server and deploy the servers and the CE in the DMZ. If yes then can I have the ASA do the WCCP or the router? Thank you Regards Aiyappa

  • Import from JVC GC-FM1

    I have a Jvc GC-FM1 picsio vid cam. It shoots in 1080p 30 frames. Icannot seem to find out exactly what type of files it stores on the sd card. The only way I seem to be able to get this into FCE is to import it into Iphoto open that in Imovie Export