*********H E L P*********with SWITCH STATEMENT

I am creating a class that extends object. I am using JOptionPane for input. I have a switch statement that I am using to call other methods, such as displaying a flag using GraphicsPen. Everything works great except when the switch calls the flag method and displays the flag, I can't close the flag until I end the switch method. I have a " for(;;) " statement that encloses the main method so the switch method will continue after each iteration.*********HELP*********PLEASE!*****************

class switchflags extends Object //class declaration
public static void main (String[]args) //main method
final String TITLE = "SWITCH"; //title for dialogs
for (;;) //loop
String switchstring = JOptionPane.showInputDialog //dialog for input
(null,"Select which program you want to use from below.\n\n"+
"*******Press enter when finished*******\n\n"+
"Enter 0 : to Quit\n"+
"Enter 1 : to see the Dutch Flag\n"+
"Enter 2 : to see the Mauritius Flag\n"+
"Enter 3 : to see the Italian Flag\n"+
"Enter 4 : to see the Norwegian Flag\n"+
"Enter 5 : to calculate Fibonacci number (n)\n"+
"Enter 6 : to calculate Miles Per Gallon\n\n",TITLE,JOptionPane.INFORMATION_MESSAGE);
int switchint = Integer.parseInt(switchstring); //convert string to a integer
if (switchint == 0) //exit if 0 was entered
JOptionPane.showMessageDialog
(null,"Thanks for using this program.\nHave a nice day!",TITLE,JOptionPane.PLAIN_MESSAGE);
System.exit(0); //end program
else if (switchint < 0) //show error for invalid numbers less than zero
JOptionPane.showMessageDialog
(null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
TITLE,JOptionPane.ERROR_MESSAGE);
else if (switchint > 6) //show error for invalid numbers greater than six
JOptionPane.showMessageDialog
(null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
TITLE,JOptionPane.ERROR_MESSAGE);
switch (switchint) //test variable that was entered
case 1: DutchFlag1.start(); //display Dutch flag
break;
case 2: mauritius.start(); //display Mauritius flag
break;
case 3: italy.start(); //display Italy flag
break;
case 4: norway.start(); //display Norway flag
break;
case 5: FIBONACCI.start(); //run Fibonacci program
break;
case 6: MPG.start(); //run MPG program
break;

Similar Messages

  • 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':

  • 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
    }

  • 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

  • Help with switch statement

    Hello I have a copy of my code below. Everything compiles fine its just when the code gets to the switch statement I get an error saying
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at Sample.main(Sample.java:55)
    Something is not working right when the user enters an integer expression. what can I do to fix this?
    import java.util.*;
    import java.io.*;
    // Declare a public class
    public class Sample {
         public static void main (String[] args){
         //Declare Variables
         float float0, float1;
         int int0, int1;
         String mathSign;
         char charMathSign;
         Scanner sc = new Scanner(System.in);
         //Ask user to Enter FLoating-Point Number Expression
         System.out.println("Enter a simple floating-point expression: ");
         float0 = sc.nextFloat();
         mathSign = sc.next ();
         float1 = sc.nextFloat();
         if(mathSign.equals("+"))
         System.out.println(float0 + " + " + float1 + " = " + (float0 + float1));     
         else if(mathSign.equals("-"))
         System.out.println(float0 + " - " + float1 + " = " + (float0 - float1));
         else if(mathSign.equals("*"))
         System.out.println(float0 + " * " + float1 + " = " + (float0 * float1));
         else if(mathSign.equals("/"))
         System.out.println(float0 + " / " + float1 + " = " + (float0 / float1));
         //Ask the user to enter a simple floating point expression
         System.out.println("Enter a simple integer expression: ");
         int0 = sc.nextInt ();
         charMathSign = mathSign.charAt(0);
         int1 = sc.nextInt ();
         switch (charMathSign)
              case '+': System.out.println(int0 + " + " + int1 + " = " + (int0 + int1));
              break;
              case '-': System.out.println(int0 + " - " + int1 + " = " + (int0 - int1));
              break;
              case '*': System.out.println(int0 + " * " + int1 + " = " + (int0 * int1));
              break;
              case '/': System.out.println(int0 + " / " + int1 + " = " + (int0 / int1));
              break;
    [/code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    {color:#000080}Duplicate posting, please post all responses at{color}{color:#0000ff}
    http://forum.java.sun.com/thread.jspa?threadID=5219239{color}{color:#000080}
    db{color}

  • 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
    }

  • DataGrid itemrenderer with switch statement

    Hi,
    I have datagrid control with this columns
    <mx:DataGrid id="dgvParagraphs" >
        <mx:columns>
            <mx:DataGridColumn dataField="type" headerText="Type"/>
            <mx:DataGridColumn dataField="title" headerText="Title"/>
            <mx:DataGridColumn dataField="content" visible="false"/>
        </mx:columns>
    </mx:DataGrid>
    Under type column I have values from 1 to 6. Each number presents type of content. I have icons for each type. I would like to show icon instead of just number. I know this can be done using itemrenderes but I don't know how to accomplish this.

    If this post answers your question or helps, please mark it as such.
    Greg Lafrance
    www.ChikaraDev.com
    Flex Development and Support Services
    You might see issues with this code during scrolling, as DataGrid recycles itemRenderers, but in that case the icon information must be in the data.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
      <mx:Script>
        <![CDATA[
          public function getImageSource(item:Object):String{
            var retVal:String;
            switch(uint(item.type)){
              case 1:
                retVal = "black.png";
                break;
              case 2:
                retVal = "blue.png";
                break;
              case 3:
                retVal = "gray.png";
                break;
              case 4:
                retVal = "green.png";
                break;
              case 5:
                retVal = "purple.png";
                break;
              case 6:
                retVal = "red.png";
                break;
            trace(retVal);
            return retVal;
        ]]>
      </mx:Script>
      <mx:DataGrid id="dgvParagraphs" dataProvider="{dataXML..item}">
        <mx:columns>
          <mx:DataGridColumn dataField="type" headerText="Type" width="50">
            <mx:itemRenderer>
              <mx:Component>
                <mx:Image source="{outerDocument.getImageSource(data)}" horizontalAlign="center"/>
              </mx:Component>
            </mx:itemRenderer>
          </mx:DataGridColumn>
          <mx:DataGridColumn dataField="title" headerText="Title" width="100"/>
          <mx:DataGridColumn dataField="content" visible="false"/>
        </mx:columns>
      </mx:DataGrid>
      <mx:XML id="dataXML" xmlns="">
        <data>
          <item>
            <type>2</type>
            <title>My Title 1</title>
            <content>Content 1</content>       
          </item>
          <item>
            <type>5</type>
            <title>My Title 2</title>
            <content>Content 2</content>
          </item>
          <item>
            <type>3</type>
            <title>My Title 3</title>
            <content>Content 3</content>
          </item>
          <item>
            <type>1</type>
            <title>My Title 4</title>
            <content>Content 4</content>
          </item>
          <item>
            <type>4</type>
            <title>My Title 5</title>
            <content>Content 5</content>
          </item>
          <item>
            <type>6</type>
            <title>My Title 6</title>
            <content>Content 6</content>
          </item>
          <item>
            <type>2</type>
            <title>My Title 7</title>
            <content>Content 7</content>
          </item>
          <item>
            <type>1</type>
            <title>My Title 8</title>
            <content>Content 8</content>
          </item>
          <item>
            <type>4</type>
            <title>My Title 9</title>
            <content>Content 9</content>
          </item>
          <item>
            <type>5</type>
            <title>My Title 10</title>
            <content>Content 10</content>
          </item>
          <item>
            <type>2</type>
            <title>My Title 11</title>
            <content>Content 11</content>
          </item>
        </data>
      </mx:XML>
    </mx:Application>

  • Problem with switching states

    Hello,
    I am currently experiencing a problem in flex 4. I have a main container that was built with catalyst, and now I am adding modules to the application. The main container has about 20 states, and each state displays a different module. At the bottom of the container is are multiple custom components, and its sole purpose is to navigate through each individual state of the main container.. We also have a logout button at the top of the container, which returns the user to the first state of the app, this logout is just a richtext component, which has a click handler. All the click handler does is
    currentState='firstState';
    This works logout text, works until I reach a certain point as the user app(as the user drills further down into the app)
    Example:
    //Each state is a state in the container
    State 1-> State 2-> State 3-> State 4->
    At state 4 the application will spit this stack out in the flash player debugger..
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at flashx.textLayout.factory::TextFlowTextLineFactory/createTextLines()[C:\Vellum\branches\v 1\1.0\dev\output\openSource\textLayout\src\flashx\textLayout\factory\TextFlowTextLineFacto ry.as:109]
        at spark.components::RichText/createTextLines()[E:\dev\4.0.0\frameworks\projects\spark\src\s park\components\RichText.as:1279]
        at spark.components::RichText/http://www.adobe.com/2006/flex/mx/internal::composeTextLines()[E:\dev\4.0.0\frameworks\pro jects\spark\src\spark\components\RichText.as:1170]
        at spark.components.supportClasses::TextBase/updateDisplayList()[E:\dev\4.0.0\frameworks\pro jects\spark\src\spark\components\supportClasses\TextBase.as:684]
        at spark.components::RichText/updateDisplayList()[E:\dev\4.0.0\frameworks\projects\spark\src \spark\components\RichText.as:1128]
        at mx.core::UIComponent/validateDisplayList()[E:\dev\4.0.0\frameworks\projects\framework\src \mx\core\UIComponent.as:8531]
        at mx.managers::LayoutManager/validateDisplayList()[E:\dev\4.0.0\frameworks\projects\framewo rk\src\mx\managers\LayoutManager.as:663]
        at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.0.0\frameworks\projects\frame work\src\mx\managers\LayoutManager.as:736]
        at mx.managers::LayoutManager/validateNow()[E:\dev\4.0.0\frameworks\projects\framework\src\m x\managers\LayoutManager.as:795]
        at mx.core::UIComponent/commitCurrentState()[E:\dev\4.0.0\frameworks\projects\framework\src\ mx\core\UIComponent.as:9822]
        at mx.core::UIComponent/setCurrentState()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\ core\UIComponent.as:9701]
        at mx.core::UIComponent/set currentState()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\core\UIComponent.as:6087 ]
        at Main/logout_Link_clickHandler()[C:\development\Main.mxml:47]
        at Main/___Main_Logout_LinkCustomComponent1_click()[C:\development\src\Main.mxml:1903]

    Please post in the DPS foum.
    http://forums.adobe.com/community/dps
    Bob

  • Methods & Switch Statement in java.. HELP!!

    hi all...
    i am having a slight problem as i am constructing a method --> menu() which handles displaying
    menu options on the screen, prompting the user to select A, B, C, D, S or Q... and then returns the user
    input to the main method!!!
    i am having issues with switch statement which processes the return from menu() methd,,,
    could you please help?!!
    here is my code...
    import java.text.*;
    import java.io.*;
    public class StudentDriver
       public static void main(String[] args) throws IOException
          for(;;)
             /* Switch statement for menu manipulation */
             switch(menu())
                   case A: System.out.println("You have selected option A");
                                  break;
                   case B: System.out.println("You have selected option B");
                                  break;
                   case C: System.out.println("You have selected option C");
                                  break;
                   case D: System.out.println("You have selected option D");
                                  break;
                   case S: System.out.println("You have selected option S");
                                  break;
                   case Q: System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                                                                    "\n\n\t\t\t Good Bye \n\n\n\n");
                                  exit(0);    
       static char menu()
          char option;
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));       
          System.out.println("\n\n");
          System.out.println("\n\t\t_________________________");
          System.out.println("\t\t|                       |");
          System.out.println("\t\t| Student Manager Menu  |");
          System.out.println("\t\t|_______________________|");
          System.out.println("\n\t________________________________________");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Add new student\t\t A \t|");
          System.out.println("\t| Add credits\t\t\t B \t|");
          System.out.println("\t| Display one record\t\t C \t|");
          System.out.println("\t| Show the average credits\t D \t|");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Save the changes\t\t S \t|");
          System.out.println("\t| Quit\t\t\t\t Q \t|");
          System.out.println("\t|_______________________________________|\n");
          System.out.print("\t  Your Choice: ");
          option = stdin.readLine();
             return option;
    }Thanking your help in advance...
    yours...
    khalid

    Hi,
    There are few changes which u need to make for making ur code work.
    1) In main method, in switch case change case A: to case 'A':
    Characters should be represented in single quotes.
    2) in case 'Q' change exit(0) to System.exit(0);
    3) The method static char menu() { should be changed to static char menu() throws IOException   {
    4) Change option = stdin.readLine(); to
    option = (char)stdin.read();
    Then compile and run ur code. This will work.
    Or else just copy the below code
    import java.text.*;
    import java.io.*;
    public class StudentDriver{
         public static void main(String[] args) throws IOException {
              for(;;) {
                   /* Switch statement for menu manipulation */
                   switch(menu()) {
                        case 'A': System.out.println("You have selected option A");
                        break;
                        case 'B': System.out.println("You have selected option B");
                        break;
                        case 'C': System.out.println("You have selected option C");
                        break;
                        case 'D': System.out.println("You have selected option D");
                        break;
                        case 'S': System.out.println("You have selected option S");
                        break;
                        case 'Q':
                        System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                        "\n\n\t\t\t Good Bye \n\n\n\n");
                        System.exit(0);
         static char menu() throws IOException {
              char option;
              BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("\n\n");
              System.out.println("\n\t\t_________________________");
              System.out.println("\t\t| |");
              System.out.println("\t\t| Student Manager Menu |");
              System.out.println("\t\t|_______________________|");
              System.out.println("\n\t________________________________________");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Add new student\t\t A \t|");
              System.out.println("\t| Add credits\t\t\t B \t|");
              System.out.println("\t| Display one record\t\t C \t|");
              System.out.println("\t| Show the average credits\t D \t|");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Save the changes\t\t S \t|");
              System.out.println("\t| Quit\t\t\t\t Q \t|");
              System.out.println("\t|_______________________________________|\n");
              System.out.print("\t Your Choice: ");
              option = (char)stdin.read();
              return option;
    regards
    Karthik

  • 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

  • Is it possible to use e.getsource with a switch statement?

    Is it possible to use e.getsource for a switch statement? I keep getting an error, which I understand. I'm just not sure if it can be done by using another method or casting e.getsource to something. Any ideas? Thanks!
         public void actionPerformed(ActionEvent e)
              switch(e.getSource())
                   //buttons 0 - 6
                   case buttons[0]:
                        Master_Clock.tickPos();
                        break;
                   case buttons[1]:
                        Master_Clock.tockPos();
                        break;
                   case buttons[2]:
                        Master_Clock.reset();
                        break;
                   case buttons[3]:
                        Master_Clock.tickNeg();
                        break;
                   case buttons[4]:
                        Master_Clock.tockNeg();
                        break;
                   case buttons[5]:
                        Master_Clock.dayPos();
                        break;
            }

    Using the same actionPerformed method for all the buttons is an obsolete technique.
    Use a seperate object implementing ActionListener with each button.
    There's a lot to be said for using Action objects, which you can also connect to key presses menu items and so on.
    Typically you create objects using the anonymous class technique. You'd do something like:
    Action tickAction = new AbstractAction("Tick") { // create anonymous action
       public void actionPerformed(ActionEvent e) {
          MasterClock.tickPos();
    JButton tickButton = new JButton(tickAction);

  • 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());
    }

  • 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;
    }

Maybe you are looking for

  • Ipad can't connect to TV after update 8.1.1

    I have an older Ipad (3rd gen. discontinued). I used to use component cables (the 3 heads one) to connect to my older TV (no HDMI)  and watch video/apps on TV with no problem.  But after the recent update ios 8.1.1. A pop up will say device not suppo

  • 8320 has lost complete signal

    Hi I purchased a uk blackberry from orange, had it unlocked to use my vodafone. I moved back to my country SA and inserted my vodacom sim. All worked well until about a week after arriving here, then it dropped signal. I removed the battery, reinsert

  • Kernel Panics on 10.6.8, please help diagnose

    Greetings, everyone. I have a macbook, 10.6.8. I just started doing kernel panics last week. It also seems to be sluggish at times. I am a bit of a 'power user' with multiple tabs and programs going at all times, but the issues are recent. Removed th

  • I can seem to install my plugins (Nik and TK-Actions from PS cc to PS 2014 Help Please.

    Need help to install nik software bundle and TK-Actions  from Photoshop cc to Photoshop 2014. I have tried copying the folders from the Plugin in folder in cc to 2014 and they seem to have arrived but the extensions option is grayed out in the Window

  • Website search widget recommendation?

    I'd like the ability to add a search function like on the top right of this forum. I spent time attempting to find a decent one using search engines, but haven't found anything good yet. Any recommendations on one that is iWeb friendly? Thanks! Dave