Switch statement with enumerated types

Hello,
I'm currently having problems (error in eclipse) using enums in a
switch block. Eclipse says:
"The enum constant Constants.AnalysisType.<each case> reference cannot be qualified in a case label.
for each of the cases that I try to use the enumerated type. My code
looks something like this:
switch (analysisType) {
case Constants.AnalysisType.NONE:
    break;
case Constants.AnalysisType.MVGAVG:
    break;
}(With a number of cases omitted).
where analysisType is the enumerated type defined in
a file called Constants.java.
The class where the error is occuring is located at:
package myprog.ui.ViewPanelTab; and the enumerated type is declared at:
package myprog.utility.Constants;I have the required import statements in the ViewPanelTab class.
I have tried
public, private, public static, private static as modifiers on the enumeration.
Any ideas as to why eclipse won't let me do this.
Thanks for any help
Devon

Why is it that the entire switch and all of its cases have the same locality ?By "locality" do you mean "scope" (i.e. the inability to declare two variables with the same name)? I find it rather irritating that I can't write switch (foo)
    case bar:
        int quux = ...
        break;
    case baz:
        int quux = ...
        break;
}My guess as to the reason for the decision to disallow this is that otherwise removing a break statement could create a compiler error where there previously was none, and that this would be confusing. It is possible to create a fresh scope, though, by using braces:switch (foo)
    case bar:
        int quux = ...
        break;
    case baz:
        int quux = ...
        break;
}

Similar Messages

  • Java Switch Statement with Strings

    Apparently you cant make a switch statement with strings in java. What is the most efficient way to rewrite this code to make it function similar to a swtich statement with strings?
    switch (type){
                   case "pounds":
                        type = "weight";
                        break;
                   case "ounces":
                        type = "weight";
                        break;
                   case "grams":
                        type = "weight";
                        break;
                   case "fluid ounces":
                        type = "liquid";
                        break;
                   case "liters":
                        type = "liquid";
                        break;
                   case "gallons":
                        type = "liquid";
                        break;
                   case "cups":
                        type = "liquid";
                        break;
                   case "teaspoons":
                        type = "liquid";
                        break;
                   case "tablespoons":
                        type = "liquid";
                        break;
              }

    I'd create a Map somewhere with entries "liquid", "weight", etc.
    public class Converter {
        private static Map<String, List<String>> unitMap = new HashMap<String, List<String>>();
        private static String[] LIQUID_UNITS = { "pints", "gallons", "quarts", "millilitres" };
        private static String[] WEIGHT_UNITS = { "pounds", "ounces", "grams" };
        static {
            List<String> liquidUnits = new ArrayList<String>();
            for (int i = 0; i < LIQUID_UNITS.length; i++) liquidUnits.add(LIQUID_UNITS));
    unitMap.put("liquid", liquidUnits);
    ... // other unit types here
    public String findUnitType(String unit) {
    for (String unitType : unitMap.keySet()) {
    List<String> unitList = unitMap.get(unitType);
    if (unitList.contains(unit))
    return unitType;
    return null;
    It might not be more "efficient", but it's certainly quite readable, and supports adding new units quite easily. And it's a lot shorter than the series of if/else-ifs that you would have to do otherwise. You'll probably want to include a distinction between imperial/metric units, but maybe you don't need it.
    Brian

  • Switch statement with JRadioButton!!!

    hi there guys....
    Good day/!
    can anyone give me some short example on switch statements with JRadioButton???

    * Radio_Test.java
    package basics;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Radio_Test extends JFrame implements ActionListener{
        public Radio_Test() {
            setTitle("Radio Test");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            buttonGroup1 = new ButtonGroup();
            toolbar = new JToolBar();
            btn1 = new JRadioButton("btn1");
            btn2 = new JRadioButton("btn2");
            btn3 = new JRadioButton("btn3");
            btn4 = new JRadioButton("btn4");
            //init button 1
            buttonGroup1.add(btn1);
            btn1.setActionCommand("1");
            btn1.addActionListener(this);
            toolbar.add(btn1);
            //init button 2
            buttonGroup1.add(btn2);
            btn2.setActionCommand("2");
            btn2.addActionListener(this);
            toolbar.add(btn2);
            //init button 3
            //init button 4
            getContentPane().add(toolbar, BorderLayout.NORTH);
            pack();
        public void actionPerformed(final ActionEvent e) {
            JRadioButton source = (JRadioButton)e.getSource();
            int action = Integer.parseInt(source.getActionCommand());
            showStatus(action);
        private void showStatus(final int action){
            switch(action){
                case 1:
                    JOptionPane.showMessageDialog(this, "Choice was 1");
                    break;
                case 2:
                    JOptionPane.showMessageDialog(this, "Choice was 2");
                    break;
                case 3:
                    JOptionPane.showMessageDialog(this, "Choice was 3");
                    break;
                default:
                    JOptionPane.showMessageDialog(this, "Choice must be 1, 2, or 3");
        public static void main(final String args[]) { new Radio_Test().setVisible(true); }
        private ButtonGroup buttonGroup1;
        private JRadioButton btn1,btn2,btn3,btn4;
        private JToolBar toolbar;
    }

  • Switch statement with println() for enum

    Hi,
    I have this exercise maybe you could help with:
    I have to create an enum class and then print out a description of each of the values from a switch.
    This is what I've done..
    enum PaperCurrency {
         FIVE, TEN, TWENTY, FIFTY, ONE_HUNDRED, TWO_HUNDRED
    public class Ex22 {
         PaperCurrency amount;
         Ex22(PaperCurrency amount) {
              this.amount = amount;
         void describe() {
              switch(amount) {
              case FIVE:               System.out.println("five dollar note");
              case TEN:               System.out.println("ten dollar note");
              case TWENTY:          System.out.println("twenty dollar note");
              case FIFTY:               System.out.println("fifty dollar note");
              case ONE_HUNDRED:     System.out.println("a hundred dollar note");
              case TWO_HUNDRED:     System.out.println("two hundred dollar note");
    static void main(String[] args) {
              Ex22
                   fiveDollars = new Ex22(PaperCurrency.FIVE),
                   tenDollars = new Ex22(PaperCurrency.TEN),
                   twentyDollars = new Ex22(PaperCurrency.TWENTY),
                   fiftyDollars = new Ex22 (PaperCurrency.FIFTY),
                   aHundredDollars = new Ex22 (PaperCurrency.ONE_HUNDRED),
                   twoHundredDollars = new Ex22 (PaperCurrency.TWO_HUNDRED);
              fiveDollars.describe();     
    }There are no compilation errors.
    The print out on the console is like this for fiveDollars.describe():
    five dollar note
    ten dollar note
    twenty dollar note
    fifty dollar note
    a hundred dollar note
    two hundred dollar note
    and it is supposed to be:
    five dollar note.
    My question is how to only print out the relevant description instead of all of them? Is my switch wrong?
    Thanks for any help

    If you can, it makes more sense to add functionality to an enum type than to write switch statements:
    public enum PaperCurrency {
        FIVE("five dollar note"),
        TEN("ten dollar note"),
        TWENTY("twenty dollar note"),
        FIFTY("fifty dollar note"),
        ONE_HUNDRED("one hundred dollar note"),
        TWO_HUNDRED("two hundred dollar note");
        private String description;
        private PaperCurrency(String desc) {
            description = desc;
        public String getDescription() {
            return description;
        public static void main(String[] args) {
            System.out.println(PaperCurrency.TEN.getDescription());
    }

  • Beginner question regarding switch statements with arrays....

    Doing a little project for my beginner's object oriented programming course. I've written the following code, but the switch statement won't recognize my array values....I'm required to use a switch statement in my program, which will count various character types in an external file....any insight is appreciated.
    import java.io.*;
    public class MyProg
      public static BufferedReader inFile;
      public static void main(String[] args)
        throws IOException, StringIndexOutOfBoundsException
        String line;
        inFile = new BufferedReader(new FileReader("TME5Part1.dat3"));
          char UpperCase[]= {'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'};          
          char LowerCase[]=     {'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'};
          char Digit[]= {'0','1','2','3','4','5','6','7','8','9'};
          char EndMark[]= {'!','.','?'};
          char MidMark[]= {',',':',';'};
        char symbol;                                                            
        int upperCaseCt = 0;                                             
        int lowerCaseCt = 0;
        int digitCt = 0;
        int endMarkCt = 0;
        int midMarkCt = 0;
          int spaceCt = 0;
          int otherCharCt = 0;
        line = inFile.readLine();          //read first line (priming read)
        while (line != null)               // Loop until end of data (empty line)
          for (int count = 0; count < line.length(); count++)  // Loop until end of line
            symbol = line.charAt(count);                    
                for (int i=0; i<=25;i++)                              
                        char uppercase=UpperCase;               //get array values for i
                        char lowercase=LowerCase[i];
                        if (i<=9) {char digit=Digit[i];}               
                        if (i<=2) {     char endmark=EndMark[i];     
                                            char midmark=MidMark[i];
                        switch(symbol)                                             
                                  case uppercase : upperCaseCt++;
                                            break;
                                  case lowercase : lowerCaseCt++;
                                                 break;
                                  case digit          : digitCt++;
                                                 break;
                                  case endmark     : endMarkCt++;
                                                 break;
                                  case midmark     : midMarkCt++;
                                                 break;
                                  case ' '          : spaceCt++;
                                                 break;
                                  default          : otherCharCt++;
                                                 break;
              line = inFile.readLine();                                   
         System.out.println("Number of uppercase letters = "+upperCaseCt);               
         System.out.println("Number of lowercase letters = "+lowerCaseCt);
         System.out.println("Nubmer of digits = "+digitCt);
         System.out.println("Number of end punctuation marks = "+endMarkCt);
         System.out.println("Number of mid punctuation marks = "+midMarkCt);
         System.out.println("Number of spaces = "+spaceCt);
         System.out.println("Number of other characters = "+otherCharCt);
    I was trying to do it this way rather than "case 'A':
    case 'B':
    case 'Z:" for each type of 'symbol'.
    Unfortunately, the switch statement is required or this would be easier with arrays and for loops...I'm not sure if my code is even possible. Thanks in advance =)
    Edited by: RiTarDid

    RiTarDid wrote:
    For sure it is the most straightforward way, but my curiosity is getting the better of me....I will most likely submit the program with the longer (value-by-value) switch method, as I haven't found anyone who can tell me how to properly reference an array value in a 'case'.Well, you can do this (basically):
    switch(some_array[some_index]) {
        case 'a':  blahblah
        case 'z':  blahblah
    }What you can't do is this:
    switch(some_scalar_value) {
      case a_whole_array:  blahblah
      case a_whole_another_array: blahblah
    }Because the latter isn't what "case" means.
    If you want to do something like the latter, use if/else statements. Here's a dirty little industry secret: people seldom use switch/case. if/else is a lot more common.
    Actually that dirty little secret isn't really particular dirty or particularly secret. It is, however, little.
    I just recall a suggestion to use arrays for any group that is more than 10 values in size;Well...sort of...
    You should use the expression of data that's appropriate for what the data is. If it's a collection of data of the same kind and an ordering, then an array or a java.util.List makes sense. If it's data that is of the same kind but no ordering and no duplicates are allowed, use a java.util.Set. (Etc. on this front.) If it's a collection of un-alike data, but which belongs in associated groups (e.g., a user's name, age, height, and whether s/he's married) then you should create a class that represents that logical grouping. Etc. If you have more than 10 individual data that can't be grouped or collected somehow, then chances are you need to rethink what's happening.
    so I wanted to see if an array could be employed for comparisons with the 'switch' statement. The program is simple enough, I'm just trying to flex my problem-solving muscle in different ways. :)
    thanks for replying, hope I can get a definite "yes, it can be done this way" or "no it can't" if there's anyone out there who knows.....The problem is that your example is contrived. So you can do a variety of things that fit into the contrivance, but they'd be weird things.
    In practice, you'd want to use the character classification methods in Character, if you wanted to characterize a bunch of characters. Or maybe a regular expression. There's no need to keep an array of characters to match against if you want to determine whether a particular character is upper case. In fact, that's the wrong way of doing things, because Character.isUpperCase is more likely to tell whether any character (not just stuff that's also an element of ASCII) qualifies as upper case.

  • Problems with enumerated type and DataSocket

    I am publishing an enumerated type variable using DataSocket write and I am having problems subscribing to this with other clients on the network. I can get the program to work ok if I replace the enumerated type with a straight numeric or a Text Ring for example. Is there anything special I should be looking out for when using enumerated types in this type of application.
    Thanks Kelly

    Updating to the latest version of LabVIEw (6.0.2) should correct this problem:
    http://digital.ni.com/softlib.nsf/websearch/F983BDA17B8F401B862569EC005A11C2
    Also, I would suggest updating to the latest version DataSocket:
    http://digital.ni.com/softlib.nsf/web%2Fall%20software?OpenView&Start=1&Count=500&Expand=6#6
    Chris_Mitchell
    Product Development Engineer
    Certified LabVIEW Architect

  • How to Use Switch Statement with Exclusion Group (radio buttons)?

    Wouldn't you know, just when I though I'd really be making progress, I've come across another problem I can't solve. In a homeowners insurance application I am building, there is an exclusion group that needs to set the value of several variables
    I have setup in the form properties/variables. These variables take on different values depending on the users choice.  For the exclusion group, in the object pallet, I have set the binding to normal, and have checked the "Specify Item Values" check box. Also the values for the choices have been assigned 1,2,3,4,5.
    Here is my code for the change event fir the exclusion group (This is exactly what I have tried). For now, the values for the variables to take on in the different cases, are completely arbitrary.
    switch (this.change.rawValue)              // I have tried so many things here
        case "1":                                        // I have tried the caption, single quotes in all combinations
            addLivingExp = "1";
            damageOthersProperty = "2";
            liabilityIncl = "3";
            maxCoverage = "4";
            minCoverage = "5";
            persProperty = "6";
            relatedPrivateStruct = "7";
            break;
        case "2":    
            addLivingExp = "10";
            damageOthersProperty = "20";
            liabilityIncl = "30";
            maxCoverage = "40";
            minCoverage = "50";
            persProperty = "60"
            relatedPrivateStruct = "70";
            break;
        case "3":    
            addLivingExp = "100";
            damageOthersProperty = "200";
            liabilityIncl = "300";
            maxCoverage = "400";
            minCoverage = "500";
            persProperty = "600"
            relatedPrivateStruct = "700";
            break;
        case "4":    
            addLivingExp = "1000";
            damageOthersProperty = "2000";
            liabilityIncl = "3000";
            maxCoverage = "4000";
            minCoverage = "5000";
            persProperty = "6000"
            relatedPrivateStruct = "7000";
            break;   
        case "5":    
            addLivingExp = "10000";
            damageOthersProperty = "20000";
            liabilityIncl = "30000";
            maxCoverage = "40000";
            minCoverage = "50000";
            persProperty = "60000"
            relatedPrivateStruct = "70000";
            break;   
        default:   
            minCoverage= 5;   
            break;
    There must be something obvious I am missing? Eternally grateful for advice on this.
    Stephen

    There are two issues in this script:
    1. You are not using the accessor 'value' to set form variables
    2. You are not correctly getting the value of the radio button list in the switch clause
    Please see the working script below.
    Ben Walsh
    www.avoka.com
    switch (this.rawValue) 
        case "1":                                       
            addLivingExp.value                  = "1";
            damageOthersProperty.value   = "2";
            liabilityIncl.value                      = "3";
            maxCoverage.value                 = "4";
            minCoverage.value                  = "5";
            persProperty.value                  = "6";
            relatedPrivateStruct.value        = "7";
            break;
        case "2":   
            addLivingExp.value                  = "10";
            damageOthersProperty.value   = "20";
            liabilityIncl.value                     = "30";
            maxCoverage.value                 = "40";
            minCoverage.value                  = "50";
            persProperty.value                  = "60"
            relatedPrivateStruct.value        = "70";
            break;
        case "3":   
            addLivingExp.value                 = "100";
            damageOthersProperty.value   = "200";
            liabilityIncl.value                     = "300";
            maxCoverage.value                 = "400";
            minCoverage.value                  = "500";
            persProperty.value                  = "600"
            relatedPrivateStruct.value        = "700";
            break;
        case "4":   
            addLivingExp.value                  = "1000";
            damageOthersProperty.value   = "2000";
            liabilityIncl.value                      = "3000";
            maxCoverage.value                 = "4000";
            minCoverage.value                  = "5000";
            persProperty.value                  = "6000"
            relatedPrivateStruct.value        = "7000";
            break; 
        case "5":   
            addLivingExp.value                  = "10000";
            damageOthersProperty.value   = "20000";
            liabilityIncl.value                      = "30000";
            maxCoverage.value                 = "40000";
            minCoverage.value                  = "50000";
            persProperty.value                  = "60000"
            relatedPrivateStruct.value        = "70000";
            break; 
        default:  
            minCoverage.value                 = 5;  
            break;

  • Error with enumerator types while building KVM.

    Porting KVM to the iPAQ hw6515, and I'm getting the following error whie compiling the code in Visual Studio 2005:
    machine_md.h(133) : error C2365: 'PVM_NoAccess' : redefinition; previous definition was 'enumerator'
    Here's the source code line:
    enum { PVM_NoAccess, PVM_ReadOnly, PVM_ReadWrite };This error indicates that I'm trying to redefine PVM_NoAccess. Any one know why this error would occur. Doesn't make sense.
    Thanks.

    my part of JPD file from where i am calling db method which query the records.
    * @jpd:process process::
    * <process name="loadContacts">
    * <clientRequest name="Subscription" method="subscription"/>
    * <perform name="Perform" method="CacheRecordType"/>
    * <block name="Group">
    * <onException name="OnException">
    * <perform name="Perform" method="perform1"/>
    * </onException>
    * <doWhile name="Do While" condition="exprFunction0($rowsProcessed)">
    * <perform name="Perform" method="perform"/>
    * </doWhile>
    * </block>
    * </process>::
    * @jpd:xquery prologue::
    * define function exprFunction0(xs:int $rowsProcessed) returns xs:boolean {
    * ($rowsProcessed <= 50) and
    * ($rowsProcessed != 0)
    public void perform() throws Exception
    LoginResult loginResult=null;
    String sforceId="";
    SvcControl.ContactData[] contactData = null;
    log.debug("Started Load Contact process=");
    try{
    log.debug("Started Load Contact process="+ SvcControl.getContactData().toString());
    contactData = SvcControl.getContactData();
    log.debug("Started Load Contact process="+ contactData.toString());
    }catch(Exception e){
    log.error("Caught exception:"+e.getMessage());
    return;
    if(contactData!=null){
    Edited by: Pannar on Dec 4, 2008 10:45 PM

  • Default case not working in a switch statement

    I get a run-time error when i input other flavor than the three listed in the code.
    Any comments and suggestions are welcomed.
    import java.util.Scanner;
    public class EnumSwitchDemo
         enum Flavor {VANILLA, CHOCOLATE, STRAWBERRY};
         public static void main(String[] args)
              Flavor favorite = null;
              Scanner keyboard = new Scanner(System.in);
              System.out.println("What is your favorite flavor? ");
              String answer = keyboard.next();
              answer = answer.toUpperCase();
              favorite = Flavor.valueOf(answer);          
              switch(favorite)
                   case VANILLA:
                        System.out.println("Classic");
                        break;
                   case CHOCOLATE:
                        System.out.println("Rich");
                        break;
                   case STRAWBERRY:
                        System.out.println("Tasty");
                        break;
                   default:
                        System.out.println("Sorry, Flavor unavailable");
                        break;
    }

    Yes, the static valueOf method of an Enum type throws an IllegalArgumentException, if the name is not defined, I think. So the problem is not the switch statement.
    Btw, normally you don't need switch statements with enums, since you can define methods in enums.
    -Puce

  • Problem with switch statement

    Here's my dilemma,
    I'm trying to write a program that takes a user input ZIP Code and then outputs the geographical area associated with that code based on the first number. My knowledge of Java is very, very basic but I was thinking that I could do it with the charAt method. I can get the input fine and isolate the the first character but for some reason the charAt method is returning a number like 55 (that's what I get when it starts with 7). Additionally, to use the charAt my input has to be a String and I can't use a String with the switch statement. To use my input with the Switch statement I have to make the variable an int. When I do that however, I can't use the charAt method to grab the first digit. I'm really frustrated and hope someone can point me in the right direction.
    Here's what I have so far:
    import java.util.Scanner;
    public class ZipCode
         public static void main(String[] args)
              // Get ZIP Code
              int zipCodeInput;
              Scanner stdIn = new Scanner(System.in);
              System.out.print("Please enter a ZIP Code: ");
              zipCodeInput = stdIn.nextInt();
              // Determine area of residence
              switch (zipCodeInput)
                   case 0: case 2: case 3:
                        System.out.println(zipCodeInput + " is on the East Coast");
                        break;
                   case 4: case 5: case 6:
                        System.out.println(zipCodeInput + " is in the Central Plains area");
                        break;
                   case 7:
                        System.out.println(zipCodeInput + " is in the South");
                        break;
                   case 8: case 9:
                        System.out.println(zipCodeInput + " is int he West");
                        break;
                   default:
                        System.out.println(zipCodeInput + " is an invalid ZIP Code");
                        break;
    }

    Fmwood123 wrote:
    Alright, I've successfully isolated the first number in the zip code by changing int zipCodeChar1 into char zipCodeChar1. Now however, when I try to run that through the switch I get the default message of <ZIP> is an invalid ZIP Code. I know that you said above that switch statements were bad so assume this is purely academic at this point. I'd just like to know why it's not working.
    import java.util.Scanner;
    public class ZipCode
         public static void main(String[] args)
              // Get ZIP Code
              String zipCodeInput;
              char zipCodeChar1;
              Scanner stdIn = new Scanner(System.in);
              System.out.print("Please enter a ZIP Code: "); // Input of 31093
              zipCodeInput = stdIn.nextLine();
              System.out.println("zipCodeInput is: " + zipCodeInput); // Retuns 31093
              zipCodeChar1 = zipCodeInput.charAt(0);
              System.out.println("zipCodeChar1 is: " + zipCodeChar1); // Returns 3
              // Determine area of residence
              switch (zipCodeChar1)
                   case 0: case 2: case 3:
                        System.out.println(zipCodeInput + " is on the East Coast");
                        break;
                   case 4: case 5: case 6:
                        System.out.println(zipCodeInput + " is in the Central Plains area");
                        break;
                   case 7:
                        System.out.println(zipCodeInput + " is in the South");
                        break;
                   case 8: case 9:
                        System.out.println(zipCodeInput + " is int he West");
                        break;
                   default:
                        System.out.println(zipCodeInput + " is an invalid ZIP Code");
                        break;
    When you print the char '7' as a character you will see the character '7', but char is really a numeric type: think of it as unsigned short. To convert '0'...'9' to the numbers 0...9, do the math:
    char ch = ...
    int digit = ch - '0';edit: or give your cases in terms of char literals:
    case '0': case '2': case '3':

  • Having problem with switch statement..please help

    here my question :
    GUI-based Pay Calculator
    A company pays its employees as executives (who receive a fixed weekly salary) and hourly workers (who receive a fixed hourly salary for the first 40 hours they work in a week, and 1.5 times their hourly wage for overtime worked).
    Each category of employee has its own paycode :
    ?     Paycode 1 for executives
    ?     Paycode 2 for hourly workers
    Write a GUI-based application to compute the weekly pay for each employee. Use switch to compute each employee?s pay based on that employee?s paycode.
    Use CardLayout layout manager to display appropriate GUI components. Obtain the employee name, employee paycode and other necessary facts from the user to calculate the employee?s pay based on the employee paycode:
    ?     For paycode 1, obtain the weekly salary.
    ?     For paycode 2, obtain the hourly salary and the number of hours worked.
    You may obtain other information which you think is necessary from the user.
    Use suitable classes for the GUI elements. (You can use javax.swing package or java.awt package for the GUI elements.)
    here my code so far :
    import java.awt.;*
    import java.awt.event.;*
    import javax.swing.;*
    *public class PayrollSystem implements ItemListener {*
    JPanel cards, JTextField, textField1, JLabel, label1;
    final static String EXECUTIVEPANEL = "1.EXECUTIVE";
    final static String HOURLYPANEL = "2.HOURLY WORKER";
    public void addComponentToPane(Container pane)
    *//Put the JComboBox in a JPanel to get a nicer look.*
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    JPanel userNameAndPasswordPane = new JPanel();
    *// User Name JLabel and JTextField*
    userNameAndPasswordPane.add(new JLabel("NAME"));
    JTextField textField1 = new JTextField(25);
    userNameAndPasswordPane.add(textField1);
    *String comboBoxItems[] = { EXECUTIVEPANEL, HOURLYPANEL };*
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    *//Create the "cards".*
    JPanel card1 = new JPanel();
    card1.add(new JLabel("WEEKLY SALARY"));
    card1.add(new JTextField(6));
    card1.add(new JLabel("TOTAL PAY"));
    card1.add(new JTextField(8));
    card1.add(new JButton("CALCULATE"));
    JPanel card2 = new JPanel();
    card2.add(new JLabel("HOURLY SALARY"));
    card2.add(new JTextField(6));
    card2.add(new JLabel("TOTAL HOURS WORK"));
    card2.add(new JTextField(8));
    card2.add(new JButton("CALCULATE"));
    *//Create the panel that contains the "cards".*
    cards= new JPanel(new CardLayout());
    cards.add(card1, EXECUTIVEPANEL);
    cards.add(card2, HOURLYPANEL);
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(userNameAndPasswordPane, BorderLayout.CENTER);
    pane.add(cards, BorderLayout.PAGE_END);
    public void itemStateChanged(ItemEvent evt)
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    ** GUI created*
    *private static void createAndShowGUI() {*
    *//Make sure we have nice window decorations.*
    JFrame.setDefaultLookAndFeelDecorated(true);
    *//Create and set up the window.*
    JFrame frame = new JFrame("GUI PAY CALCULATOR");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    *//Create and set up the content pane.*
    PayrollSystem demo = new PayrollSystem();
    demo.addComponentToPane(frame.getContentPane());
    *//Display the window.*
    frame.pack();
    frame.setVisible(true);
    *public static void main(String[] args) {*
    *//Schedule a job for the event-dispatching thread:*
    *//creating and showing this application's GUI.*
    *javax.swing.SwingUtilities.invokeLater(new Runnable() {*
    *public void run() {*
    createAndShowGUI();
    HOW CAN I PERFORM THE SWITCH STATEMENT INSIDE THIS CODE TO LET IT FULLY FUNCTIONAL..?
    I MUST PERFORM THE SWITCH STATEMENT LIKE IN THE QUESTION..
    PLEASE HELP ME..REALLY APPRECIATED...TQ

    hi
    A switch works with the byte, short, char, and int primitive data types. So you can simply give the
    switch (month) {
                case 1: 
                            System.out.println("January");
                            break;
                case 2:  {
                            System.out.println("February");
                             break;
                case 3: {
                              System.out.println("March");
                              break;
                             }where month controlls the flow
    moreover u can go to http://www.java-samples.com/java/free_calculator_application_in_java.htm
    for reference, just replace the if statement with switch with correct syntax

  • Problems with switch statement

    He everyone,
    i tried to built a page with 4 buttons. Each button is a symbol that contains 2 png´2 which are the the button Designs. If you click on  button 1 it should move on the screen. If you click it again it should moves back. and if you click on another button while button1 is active then button1 should move back to starting position and button 2 should move on screen.
    i use a switch statement and a variable.
    on composition ready i used
    sym.setVariable("current","");
    to set the Variable
    on each button(one of the png inside the symbols) i used:
    var current = sym.getComposition.getStage.getVariable("current");
    switch (current)
    case "" :
    sym.play("in");
    break;
    case button1 :
    sym.play("out");
    break;
    default :
    sym.getComposition.getStage.getSymbol(current).play("out");
    sym.play("in");
    break;
    ad each animation of the buttons are labels for the in and out animation. There are also triggers that change the variable current on the stage
    sym.getComposition.getStage.setVariable("current","button1");
    if i test it inside of a browser and click on one of the button nothing happens.
    i´m not sure what´s my mistake.
    can anyone help me?
    regards
    mr.monsen

    Hi,
    Some syntax errors in red:
    var current = sym.getComposition().getStage().getVariable("current");
    switch (current)
    case "" :
    sym.play("in");
    break;
    case "button1" :
    sym.play("out");
    break;
    default :
    sym.getComposition().getStage().getSymbol(current).play("out");
    sym.play("in");
    sym.getComposition().getStage().setVariable("current","button1");

  • Problem with switch-statement & ä, ö, ü

    Hi all,
    I am doing this Java online tutorial right now and have a problem with one of the exercises. Hopefully you can help me:
    I have to write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line. I found a solution, but have two questions about it:
    •     I’m unable to calculate the amount of umlauts (ä, ö, ü). Somehow the program doesn’t recognize those characters. Why?
    •     In general I’m not very happy with this huge list of “cases”. How would you solve a problem like this? Is there a more convenient/elegant way?
    Thanks in advance!
    Write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line.
    Read in the line into a String (in the usual way). Now use the charAt() method in a loop to access the characters one by one.
    Use a switch statement to increment the appropriate variables based on the current character. After processing the line, print out
    the results.
    import java.util.Scanner;
    class Kap43A1
      public static void main ( String[] args )
        String line;
        char letter;
        int total, countV=0, countC=0, countS=0, countU=0, countP=0;
        Scanner scan = new Scanner(System.in);
        System.out.println( "Please write a sentence " );
        line = scan.nextLine();
        total=line.length(); //Gesamtanzahl an Zeichen des Satzes
        for (int counter=0; counter<total; counter++)
          letter = line.charAt(counter); //ermitteln des Buchstabens an einer bestimmten Position des Satzes
          switch (letter)
            case 'A': case 'a':
            case 'E': case 'e':
            case 'I': case 'i':
            case 'O': case 'o':
            case 'U': case 'u':
              countV++;
              break;
            case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h':
            case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'P': case 'p':
            case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'V': case 'v': case 'W': case 'w':
            case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z':
              countC++;
              break;
            case ' ':
              countS++;
              break;
            case ',': case '.': case ':': case '!': case '?':
              countP++;
              break;
            case 'Ä': case 'ä': case 'Ö': case 'ö': case 'Ü': case 'ü':
              countU++;
              break;
        System.out.println( "Total amount of characters:\t" + total );
        System.out.println( "Number of consonants:\t\t" + countC );
        System.out.println( "Number of vocals:\t\t" + countV );
        System.out.println( "Number of umlauts:\t\t" + countU );
        System.out.println( "Number of spaces:\t\t" + countS );
        System.out.println( "Number of punctuation chars:\t" + countP );
    }

    WRE wrote:
    •In general I’m not very happy with this huge list of “cases”. How would you solve a problem like this? Is there a more convenient/elegant way?I've been doing this a lot lately myself evaluating documents with 20 or so million words. Few tips:
    1. Regular expressions can vastly reduce the list of cases. For example you can capture all letters from a to z or A to Z as follows [a-zA-Z]. To match a single character in a String you can then make use of the Pattern and Matcher classes, and incorporate the regular expression. e.g.
      //Un-compiled code, may contain errors.
      private Pattern letterPattern = Pattern.compile("[a-zA-Z]");
      public int countNumberOfLettersInString(final String string) {
        int count = 0;
        Matcher letterMatcher = letterPattern.matcher(string);
        while(letterMatcher.find()) {
          count++;
        return count;
      }2. As mentioned above, Sets are an excellent choice. Simply declare a static variable and instantiate it using a static initializer block. Then loop over the String to determine if the character is in the given set. e.g.
      //Un-compiled code, may contain errors.
      private static Set<Character> macrons = new HashSet<Character>();
      static {
        macrons.add('ä');
        macrons.add('ö');
        macrons.add('ü');
      public int countNumberOfMacronsInString(final String string) {
        int count = 0;
        for(char c : string.toCharArray()) {
          if(macrons.contains(c) {
            count++;
        return count;
      }Mel

  • Help with Switch statements using Enums?

    Hello, i need help with writing switch statements involving enums. Researched a lot but still cant find desired answer so going to ask here. Ok i'll cut story short.
    Im writing a calculator program. The main problem is writing code for controlling the engine of calculator which sequences of sum actions.
    I have enum class on itself. Atm i think thats ok. I have another class - the engine which does the work.
    I planned to have a switch statement which takes in parameter of a string n. This string n is received from the user interface when users press a button say; "1 + 2 = " which each time n should be "1", "+", "2" and "=" respectively.
    My algorithm would be as follows checking if its a operator(+) a case carry out adding etc.. each case producing its own task. ( I know i can do it with many simple if..else but that is bad programming technique hence im not going down that route) So here the problem arises - i cant get the switch to successfully complete its task... How about look at my code to understand it better.
    I have posted below all the relevant code i got so far, not including the swing codes because they are not needed here...
    ValidOperators v;
    public Calculator_Engine(ValidOperators v){
              stack = new Stack(20);
              //The creation of the stack...
              this.v = v;          
    public void main_Engine(String n){
           ValidOperators v = ValidOperators.numbers;
                    *vo = vo.valueOf(n);*
         switch(v){
         case Add: add();  break;
         case Sub: sub(); break;
         case Mul: Mul(); break;
         case Div: Div(); break;
         case Eq:sum = stack.sPop(); System.out.println("Sum= " + sum);
         default: double number = Integer.parseInt(n);
                       numberPressed(number);
                       break;
                      //default meaning its number so pass it to a method to do a job
    public enum ValidOperators {
         Add("+"), Sub("-"), Mul("X"), Div("/"),
         Eq("="), Numbers("?"); }
         Notes*
    It gives out error: "No enum const class ValidOperators.+" when i press button +.
    It has nothing to do with listeners as it highlighted the error is coming from the line:switch(v){
    I think i know where the problem is.. the line "vo = vo.valueOf(n);"
    This line gets the string and store the enum as that value instead of Add, Sub etc... So how would i solve the problem?
    But.. I dont know how to fix it. ANy help would be good
    Need more info please ask!
    Thanks in advance.

    demo:
    import java.util.*;
    public class EnumExample {
        enum E {
            STAR("*"), HASH("#");
            private String symbol;
            private static Map<String, E> map = new HashMap<String, E>();
            static {
                put(STAR);
                put(HASH);
            public String getSymbol() {
                return symbol;
            private E(String symbol) {
                this.symbol = symbol;
            private static void put(E e) {
                map.put(e.getSymbol(), e);
            public static E parse(String symbol) {
                return map.get(symbol);
        public static void main(String[] args) {
            System.out.println(E.valueOf("STAR")); //succeeds
            System.out.println(E.parse("*")); //succeeds
            System.out.println(E.parse("STAR")); //fails: null
            System.out.println(E.valueOf("*")); //fails: IllegalArgumentException
    }

  • Help With Switch Statements

    Alrighty, so I have to do this assignment for my Java course, using a switch statement. The assignment is to have the user enter a number (1-5), and have the corresponding line of a poem be displayed. So if the user entered 1, "One two, buckle your shoe" would be displayed. This is what I have and it's giving me a huge problem:
    import java.util.Scanner;
    public class Poem
         public static void main(String[] args);
              Scanner kboard = new Scanner(System.in);
              System.out.println("Enter a number 1-5 (or 0 to quit).");
              int n = kboard.nextLine();
              switch (n);
                   case 1: System.out.println("One two, buckle your shoe.");
                   break;
                   case 2: System.out.println("Three four, shut the door.");
                   break;
                   case 3: System.out.println("Five six, pick up sticks.");
                   break;
                   case 4: System.out.println("Seven eight, lay them straight.");
                   break;
                   case 5: System.out.println("Nine ten, a big fat hen.");
                   break;
                   default: System.out.println("Goodbye.");
                   break;
    }This is giving me a HUGE string of errors. (Something like 45). I'm wracking my brain here trying to figure this out. Any help is greatly appreciated. Thanks!

    Well that solved a lot of the errors. Now all I get is this:
    --------------------Configuration: <Default>--------------------
    C:\JavaPrograms\Poem.java:8: <identifier> expected
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:8: illegal start of type
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:12: illegal start of type
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:12: <identifier> expected
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:14: orphaned case
    case 1: System.out.println("One two, buckle your shoe.");
    ^
    C:\JavaPrograms\Poem.java:30: class, interface, or enum expected
    }

Maybe you are looking for

  • Unable to unistall Cisco AnyConnect VPN - please help

    I have upgraded to Windows 8.1 preview on my Surface Pro. My Cisco AnyConnect VPN stopped working. When I uninstalled the software it left the 'Cisco AnyConnect VPN Virtual Miniport Adapter for Windows x64' under the network adapters in Device Manage

  • How do you integrate a column with respect to another column

    I have two columns of data, one is time and the other is velocity. I want to be able to integrate velocity with respect to time, but I can not find a function which will let me do this. Preferably, I'd like to do a cumulative trapezoidal integration,

  • Import failed error in NWDI  SAP_PSS

    Hi Experts, I have a problem in NWDI which is  I created once DC in SAP_PSS component and during the development we had a problem in desktop and lost complete data in local machine. By that time my activity is released but ! that results broken DC. 

  • Macbook Pro won't startup after installing of 10.8.4

    I just installed the 10.8.4 combo update package anf my Macbok Pro won't restart. After downloading the updates, the computer restarted itself, finished installing the updates, restarted itsalf again, anf when it gets to the gray screen with the Appl

  • How to Visualize 3D data in Labview.

    Hi,  I am using Labview 2010,i have a 3D point cloud that i created in PCL(point cloud library).Now, I want to know if there is a 3D visualizer in Labview that will let me visualize the data if i send it the array/file of 3D points as input.I know th