Switch statement to java string

Hello!
I am programing a form in jsp that will send an e-mail to different people , depending on the selection of a SELECT box.
I am using a Bean which will take the option chosen in the select and then prepare the message.
My problem is that the option list has a lot of values and I would like to use the switch statement , but I always receive a compilation error since the switch statement only allows int and I am using a String....
Should I use a nested if in that case...or there is another solution?
================
Form.html
Region <SELECT NAME="region">
<OPTION VALUE="SouthEastEurope">South East Europe</OPTION>
<OPTION VALUE="Italy">Italy</OPTION>
<OPTION VALUE="SouthernAfrica">Southern Africa</OPTION>
<OPTION VALUE="France">France</OPTION>
<OPTION VALUE="NorthernAfrica">Northern Africa</OPTION>
<OPTION VALUE="MiddleEast">Middle East</OPTION>
<OPTION VALUE="Iberia">Iberia</OPTION>
</SELECT><P>....
==============================
SendMail.java
switch(region)
                    case SouthEastEurope:
                         toAddress = "[email protected]";
                         break;
                    case Italy:
                         toAddress = "[email protected]";
                         break;
........and so on.....
               }

How about generating a Map to match the country to an address.
Map mymap = new HashMap();
mymap.put("SouthEastEurope", "[email protected]");
mymap.put("Italy", "[email protected]");
String toadress = (String) mymap.get(region);Saves you from a horrible switch statement.

Similar Messages

  • 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

  • Using a Switch statement for Infix to Prefix Expressions

    I am stuck on the numeric and operator portion of the switch statement...I have the problem also figured out in an if/else if statement and it works fine, but the requirements were for the following algorithm:
    while not end of expression
    switch next token of expression
    case space:
    case left parenthesis:
    skip it
    case numeric:
    push the string onto the stack of operands
    case operator:
    push the operator onto the stack of operators
    case right parenthesis:
    pop two operands from operand stack
    pop one operator from operator stack
    form a string onto operand stack
    push the string onto operand stack
    pop the final result off the operand stack
    I know that typically case/switch statement's can only be done via char and int's. As I said I am stuck and hoping to get some pointers. This is for a homework assignment but I am really hoping for a few pointers. I am using a linked stack class as that was also the requirements. Here is the code that I have:
       import java.io.*;
       import java.util.*;
       import java.lang.*;
    /*--------------------------- PUBLIC CLASS INFIXTOPREFIX --------------------------------------*/
    /*-------------------------- INFIX TO PREFIX EXPRESSIONS --------------------------------------*/
        public class infixToPrefix {
          private static LinkedStack operators = new LinkedStack();
          private static LinkedStack operands = new LinkedStack();
            // Class variable for keyboard input
          private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
             // Repeatedly reads in infix expressions and evaluates them
           public static void main(String[] args) throws IOException {
          // variables
             String expression, response = "y";
          // obtain input of infix expression from user
             while (response.charAt(0) == 'y') {
                System.out.println("Enter a parenthesized infix expression.");          // prompt the user
                System.out.println("Example: ( ( 13 + 2 ) * ( 10 + ( 8 / 3 ) ) )");
                System.out.print("Or as: ((13+2)*(10+(8/3))):  ");
                expression = stdin.readLine();     // read input from the user
             // output prefix expression and ask user if they would like to continue          
                System.out.println("The Prefix expression is: " + prefix(expression));     // output expression
                System.out.println("Evaluate another? y or n: ");          // check with user for anymore expressions
                response = stdin.readLine();     // read input from user
                if (response.charAt(0) == 'n') {          // is user chooses n, output the statement
                   System.out.println("Thank you and have a great day!");
                }     // end if statement
             }     // end while statement
          }     // end method main
       /*------------- CONVERSION OF AN INFIX EXPRESSION TO A PREFIX EXPRESSION ------------*/ 
       /*--------------------------- USING A SWITCH STATEMENT ------------------------------*/
           private static String prefix(String expression) {
                // variables
             String symbol, operandA, operandB, operator, stringA, outcome;
               // initialize tokenizer
             StringTokenizer tokenizer = new StringTokenizer(expression, " +-*/() ", true);     
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (expression) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case (Character.isDigit(symbol.charAt(0))):      // case numeric
                      operands.push(symbol);                                   // push the string onto the stack of operands
                      break;
                   case (!symbol.equals(" ") && !symbol.equals("(")):     // case operator
                      operators.push(symbol);                                             // push the operator onto the stack of operators
                      break;
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcome
          }     // end method prefix
       }     // end class infixToPrefixAny help would be greatly appreciated!

    so, i did what flounder suggested:
             char e = expression.charAt(0);
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (e) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case '0':
                   case '1':
                   case '2':
                   case '3':
                   case '4':
                   case '5':
                   case '6':
                   case '7':
                   case '8':
                   case '9':
                      operands.push(symbol);     // push the string onto the stack of operands
                      break;                               // case numeric
                   case '+':
                   case '-':
                   case '*':
                   case '/':
                      operators.push(symbol);     // push the operator onto the stack of operators
                      break;                               // case operator
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                   default:
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcomeafter this, I am able to compile the code free of errors and I am able to enter the infix expression, however, the moment enter is hit it provides the following errors:
    Exception in thread "main" java.lang.NullPointerException
         at LinkedStack$Node.access$100(LinkedStack.java:11)
         at LinkedStack.pop(LinkedStack.java:44)
         at infixToPrefix.prefix(infixToPrefix.java:119)
         at infixToPrefix.main(infixToPrefix.java:59)
    Any ideas as to why? I am still looking through seeing if I can't figure it out, but any suggestions? Here is the linked stack code:
        public class LinkedStack {
       /*--------------- LINKED LIST NODE ---------------*/
           private class Node {
             private Object data;
             private Node previous;
          }     // end class node
       /*--------------  VARIABLES --------------*/
          private Node top;
      /*-- Push Method: pushes object onto LinkedStack --*/     
           public void push(Object data) {
             Node newTop = new Node();
             newTop.data = data;
             newTop.previous = top;
             top = newTop;
          }     // end function push
       /*--- Pop Method: pop obejct off of LinkedStack ---*/
           public Object pop()      {
             Object data = top.data;
             top = top.previous;
             return data;
          }     // end function pop
       } // end class linked stackEdited by: drmsndrgns on Mar 12, 2008 8:10 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:14 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:26 AM

  • 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

  • HELP A COMPLETE NOOB! Java Switch Statement?

    Hi, I am trying to use a simple switch statement and I just cant seem to get it to work?;
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    String message;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    message = scan.nextLine();
    int month = 8;
    if (month == 1) {
    System.out.println("January");
    } else if (month == 2) {
    System.out.println("February");
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    Please can anyone help, all I want is to enter a number and the corresponding month to appear. Thank you.

    This will work.
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    // read user input
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    int month = scan.nextInt();
    // print the month
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    }

  • Java Program.. HELP  (switch statement)

    I need help on fixing this program for school.ive looked at information online but i still do not see what i am doing wrong.
    The College Rewards Program is based on a student�s achievements on the ACT Test. Students that have excelled on the test are going to be rewarded for the hard work that they put into high school and studying for the exam. The following are the rewards that will be given to students. They are cumulative, and they get all rewards below their score.
    1. 35-36 $100 a week spending money
    2. 33-34 Free computer
    3. 31-32 $10,000 free room and board
    4. 25-30 $5000 off the years tuition
    5. 21-24 $500 in free books per year
    6. 17-20 Free notebook
    7. 0-16 Sorry, no rewards, please study and try taking the ACT again.
    Make a prompt so the user is asked for their ACT score( be careful).
    Change the ACT score into a number
    Then have the program use that number to display a message about the Rewards program.
    Sample output:
    What was your score on the ACT: 44
    Entry error, please enter a number from 0 to 36.      (error trap wrong numbers)
    What was your score on the ACT: 27
    You got a 27 on the ACT, your rewards are:      ( have it number the rewards)
    1. $5,000 off the year�s tuition
    2. $500 dollars a year in books
    3. A free notebook
    Congratulations on your hard work and good score.
    import java.util.Scanner;
    import java.text.*;
    public class Act
        public static void main (String [] args)
             Scanner scan = new Scanner( System.in );
              int score,reward;
              score=0;
              boolean goodnum;
              do
                      System.out.println( "What was your ACT score? " );
                              score = scan.nextInt() ;
              if (score >0 || score <36) goodnum = true;      
                   else
                    System.out.println ("Please enter the correct number");
                              goodnum=false;     
                    while (score<0 || score>36) {
                              if (score==35 || score==36) reward=1;
                                   else if (score ==34 || score score==33) reward=2;
                                        else if (score==32 || score==31) reward=3;
                                             else if (score>=25 && score<=30) reward=4;
                                                  else if (score>=21 && score<=24) reward=5;
                                                     else if (score>=17 && score<=20) reward=6;
                                                              else reward=7;
        c=0
        switch (reward) {
        case 1: $100 a week spending money
                  c++
                  System.out.println ("$100 a week spending money");     
        case 2:     Free computer
                  c++
                  System.out.println ("Free computer");     
            case 3:      $10,000 free room and board
                  c++
                  System.out.println ("$10,000 free room and board");
        case 4:      $5000 off the years tuition
              c++
              System.out.println ("$5000 off the years tuition");
        case 5:      $500 in free books per year
              c++
               System.out.println ("$500 in free books per year");
        case 6:      Free notebook
              c++
              System.out.println ("Free notebook");
        case 7:      Free notebook
              c++
              System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
              break;
        default:
             System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
            break;
        }

    There are some strange things going on here that could be fixed, so I'll just put my version of how i'd handle this up.
    import java.util.Scanner;
    import java.text.*; // is this really needed? Scanner's the only class I see
    public class Act {
      public static void main( String[] args ) {
        Scanner scan = new Scanner( System.in );
        int score, reward; // don't need to set a value yet
        boolean goodnum;
        do {
          System.out.println( "What was your ACT score? " );
          score = scan.nextInt();
          if ( score >= 0 && score <= 36 ) goodnum = true; // note the && and =s
          else {
            System.out.println( "Please enter a valid number (between 0 and 36)." );
            goodnum = false;
        } while ( !goodnum ); // when this loop finished, the number will be between 0 and 36, a good number
        if ( score >= 35 ) reward = 1;      // save yourself the typing, by now score must be between 0 and 36
        else if ( score >= 33 ) reward = 2; // so just go down with else ifs.
        else if ( score >= 31 ) reward = 3; // this will only reach the lowest point.
        else if ( score >= 25 ) reward = 4;
        else if ( score >= 21 ) reward = 5;
        else if ( score >= 17 ) reward = 6;
        else reward = 7;
        // what was the c for? reward already tells how well they did
        // You handled the switch statement almost perfectly
        // don't break so that reward progressively adds to the output
        if ( reward >= 6 ) { // this if statement is optional, just for good esteem. You could even take it out of the if{}
          System.out.println( "For your score of "+String.valueOf( score )+" you will be rewarded the following:" );
        switch ( reward ) {
          case 1: // $100/week spending money
            System.out.println( "$100 a week spending money." );
          case 2: // Free computer
            System.out.println( "Free computer." );
          case 3: // $10,000 room and board
            System.out.println( "$10,000 free room and board." );
          case 4: // $5000 off tuition
            System.out.println( "$5000 off the year's tuition." );
          case 5: // $500 in free books per year
            System.out.println( "$500 in free books per year." );
          case 6: // Free notebook
            System.out.println( "Free notebook." );
            break; // break here to keep away from discouraging the fine score
          case 7: // since 7 and default are the same result, ignore this and it'll pass to default
          default: // but technically, since reward must be from 1 to 7, default would never explicitly be called
            System.out.println( "Sorry, no rewards. Please study and try taking the ACT again." );
            break; // likely this break is unneccessary
    }That works in my head, hope it works on your computer.

  • String in Switch statement

    i know char and integers are accepted by switch statements as arguments..
    me and my friend are just wondering why the creators of java doesnt included Strings...
    ex.
    case "myFirstChoice":
        {statement}
    case "mySecondChoice":
        {statement}
    case "myThirdChoice":
        {statement}etc
    we know that we can simplify it by just using char or integer as
    case 'A':
    case 'B':
    case 'C':or
    case '1':
    case '2':
    case '3':we hope someone knows the answer.. thank you very much.. have a nice day!

    The JLS says this:
    The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, such as a boxed primitive type or an enum, a run-time error will occur if the expression evaluates to null at run-time.
    It follows that if the switch expression is of an enum type, the possible values of the switch labels must all be enum constants of that type.
    Compilers are encouraged (but not required) to provide a warning if a switch on an enum-valued expression lacks a default case and lacks cases for one or more of the enum type's constants. (Such a statement will silently do nothing if the expression evaluates to one of the missing constants.) Here's the [link.|http://java.sun.com/docs/books/jls/third_edition/html/statements.html]

  • Java switch statement

    Is it possible to have a switch statement for multiple values. By this i mean, if a user types in a number between 1-3, it should print out the line
    System.out.println("Well done you got a First");break; So can i have a switch statement which is like
    case 1-3:  System.out.println("Well done you got a First");break;

    This will work:
    case 1:
    case 2:
    case 3:
       System.out.println("Well done you got a First");
    break;No, there's no way to express a "range" in a case statement though.

  • Shortening 'if' statement in Java.

    Hey guys. I'm pretty new to Java and up until now I've never had a problem using if statements. I understand the case statement (switch statement) is available in Java, but this usually involves the input to be a number IIRC.
    That being said, I've got some sample code that maybe somebody could explain how to shorten?
    //FIRST SET
            if (string = "a"){
                object[0].method1();}
            else
                object[0].method2();
            if (string = "b")
                object[0].method3();
            else if (string = "c")
                object[0].method4();
            else
                object[0].method5();
         //SECOND SET
         if (string = "d"){
                object[1].method1();}
            else
                object[1].method2();
            if (string = "e")
                object[1].method3();
            else if string = "f")
                object[1].method4();
            else
                object[1].method5();
            //THIRD SET
            if (string = "g"){
                object[2].method1();}
            else
                object[2].method2();
            if (string = "h")
                object[2].method3();
            else if (string = "i")
                object[2].method4();
            else
                object[2].method5();Basically, it's about 30 lines that I could probably fit into 15 or so if I knew how to shorten it. I think it's fairly straight-forward, but if not, the whole point is that "object" is an array of realistically any number (for the sake of this, it's 3). However, it could also be 2 or 1. Automatically, running this gives an error if 2 or 1 are input (object[2] is out of bounds). The object will respond to a certain input string (I know the if statement is not in correct -- this was just the easier) and will run a method based on that string.
    Anybody know how to shorten this, and make sure that any number of objects in the array can work?
    Thanks for the help.

    LordSleepy wrote:
    LordSleepy wrote:The object will respond to a certain input string (I know the if statement is not in correct -- this was just the easier)I had already explained that. It should have been apparent that it was a sample, it didn't actually do anything, and therefore, the syntax was probably the last thing I needed to correct.I disagree. Your sample should convey what you are trying to do. The code you showed us did nothing at all, because it did not compile.
    If you don't want to care about syntax too much, then better use pseudo-code, such as this:
    if string is "a" then
      call method1
    else
      call method2Here you can use whatever syntax you want, but if your code looks almost like Java code but doesn't compile, then it's a bad example, even if you just want to demonstrate something.
    UPDATE then, I need to take keystrokes (represented here as the strings, although I have a method that responds correctly and does not actually involve strings at all), but I was hoping I could take it from a lot of 'if statements' to something less... drawn out. As you can see, the first "set" is exactly the same as the second and third, except that the object[array] changes from 1 to 2 to 3, and the keystroke varies between a set number of keys. Generally when you have these kind of it-then-else cascades, there's a more object oriented approach that will be a lot cleaner.
    You could, for example, create a Command object for each keystroke (or String in your example) and just put that into a Map indexed by the keystroke/String.
    Command would be a interface with a simple execute() method (optionally providing any context those commands generally need) and your could just fetch the correct Command and call execute().
    This way each class (Command) has a exactly defined task, you can easily add new commands and you get rid of those ugly if-then-else rows.
    An even more general suggestion: If your code looks as if it does the same thing again and again with only slight variations, then you should definitely look into a different design.

  • HELP -menu using a switch statement

    Hello to all. I'm new to the Java world, but currently taking my first Java class online. Not sure if this is the right place, but I need some help. In short I need to write a program that gives the user a menu to chose from using a switch statement. The switch statement should include a while statement so the user can make more than one selection on the menu and provide an option to exit the program.
    With in the program I am to give an output of all counting numbers (6 numbers per line).
    Can anyone help me with this?? If I'm not asking the right question please let me know or point me in the direction that can help me out.
    Thanks in advance.
    Here is what I have so far:
    import java.util.*;
    public class DoWhileDemo
         public static void main(String[] args)
              int count, number;
              System.out.println("Enter a number");
              Scanner keyboard = new Scanner (System.in);
              number = keyboard.nextInt();
              count = number;
              do
                   System.out.print(count +",");
                   count++;
              }while (count <= 32);
              System.out.println();
              System.out.println("Buckle my shoe.");
    }

    Thanks for the reply. I will tk a look at the link that was provided. However, I have started working on the problem, but can't get the 6 numbers per line. I am trying to figure out the problem in parts. Right now I'm working on the numbers, then the menu, and so on.
    Should I tk this approach or another?
    Again, thanks for the reply.

  • Switch Statement again

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    Yesterday, I received tremendous help, As a result, I am closer to understanding the switch statement and how it works.
    My program is designed to use 5 different input boxes. These represent a total for quizzes, homework assignments, 2 midterms, and a final exam.
    These are casted to double; then, they are added together and divided by five to obtain an average (the student's GPA). The GPA is then going to assigned a grade depending up the range in the If then statement.
    I intend on using a message box to inform the user of the GPA and another followed by another message box to show them their grade.
    I would like to incorporate the switch statement (so I can learn how to use it) to show them their grade.
    I know the code needs tweaking but this is what I have so far:
    import javax.swing.JOptionPane;
    public class Switchgrade{
    //declaration of class
    public static void main(String args[])
    //declaration of main
    String midone; String midtwo; String quiz; String homework; //declares variables to hold the grades, quiz and homework scores
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    char a; char b; char c; char d; char f;char grade;
    midone = JOptionPane.showInputDialog("Please enter the first midterm"); //first score to add
    one = Double.parseDouble(midone);
    midtwo = JOptionPane.showInputDialog("please enter second midterm"); //second midterm to add
    two = Double.parseDouble(midtwo);
    last = JOptionPane.showInputDialog("please enter final exam score");//final exam score to add
    three = Double.parseDouble(last);
    quiz = JOptionPane.showInputDialog("please enter quiz score");//quiz score to add
    four = Double.parseDouble(quiz);
    homework= JOptionPane.showInputDialog("please enter homework score");//homework score to add
    five = Double.parseDouble(homework);
    average = (one + two+ three + four + five)/5; //average of all five scores
    if(average >= 90)
    grade = 'a';
    else
    if(average >= 80 )
    grade = 'b';
    switch (grade)
    case a:
    JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");
    break;
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + b + ". \nYou failed.");
    break;
    System.exit(0);
    }//end of main
    }//end of class
    As you can see, I am only using two grades, just so I can learn to use it. However, when I go to compile this, I get this error message:
    constant expression required: case a:, with the ^ under the a.
    What does this error message me and how do I fix this.
    Thanks in advance for your help.

    case a:is trying to use a variable with the name "a" for the comparison. This is illegal in java
    what you want is
    case 'a':this will do a comparison against the char value 'a'

  • Switch Statement

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    I am trying to write an application that will calculate grades for a student. I can use the If Then Else Control structure for this (which runs) but I would like to incorporate the Switch Statement in place of the multiple if then else structure. Here is the code that I have for the application:
    import javax.swing.JOptionPane;
    public class Switchgrades
    public static void main(String args[])
    String midone; String midtwo; String quiz; String homework;
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    int a; int b; double c; double d; double f;int grade;
    midone = JOptionPane.showInputDialog("Please enter the first midterm"); //first score to add
    one = Double.parseDouble(midone);
    midtwo = JOptionPane.showInputDialog("please enter second midterm"); //second midterm to add
    two = Double.parseDouble(midtwo);
    last = JOptionPane.showInputDialog("please enter final exam score");//final exam score to add
    three = Double.parseDouble(last);
    quiz = JOptionPane.showInputDialog("please enter quiz score");//quiz score to add
    four = Double.parseDouble(quiz);
    homework= JOptionPane.showInputDialog("please enter homework score");//homework score to add
    five = Double.parseDouble(homework);
    average = (one + two+ three + four + five)/5; //average of all five scores
    switch (grade)
    case a: //this is where I become confused and lost. I don't what I need to do to make it run.
    {if(average >= 90)
         b = Integer.parseInt(average);
       JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");}
    / I am just using one choice to make it run. When I can make it run, I plan on incorporating the other grades.
    break;
    <=====================================================================>
    <=====================================================================>
    //else --->this is part of the if that works in another program
    // if(average >= 80 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a B");
    //else
    //if(average >= 70 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a C");
    //else
    //if(average >= 60 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a D");
    //else
    //if(average <= 60 )
    <=====================================================================>
    <=====================================================================>
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + average + ". \nYou failed.");
    System.exit(0);
    As you can see, I already have all the if then else statements set up--between the <==>. The program runs with the If's but I can two error messages when I incorporate the Switch statement.
    1) constant expression required.
    I have case a and i guess it is not a constant. Again, I don't understand switch well enough to figure what I need to do to correct it.
    2)"b = Integer.parseInt(average);" - cannot resolve the symbol--whatever that means. I have a "^" pointing at the period between Integer and parseInt.
    Can anyone help explain what I have to do to make this program work using Switch.
    I have not used Switch before and don't understand what I can use as opposed to what I must use for it to work.
    Thanks for your help.

    I don't really know how you want your program going, but here is what I think.
    1) From the start of the switch statement, where do you assign the value for "grade"? If you write the switch statement like below, you meant something like, if(grade == 'a'){...}, right!? Then, where did you get the "grade" from?
    switch (grade)
    case a:
    You may want declare variable "grade" as char and place if sentence like this before the switch.
    if(average >= 90)
    grade = 'a';
    else if(average >= 70)
    grade = 'b';
    switch (grade)
    case a:
    System.out.print("Your grade: A");
    break;
    case b:
    System.out.print("Your grade: A");
    break;
    Is that What you want???
    2)The method, Integer.parseInt(), takes String as parameter? Did you override this method? The variable "average" was declare as double, so why don't you just cast it to int??

  • Keyboard Input and switch statement error

    Hi,
    Below is a program to read an alphabet and check whether its a vowel/consonent using switch statement.
    Its always executin' the default stmt and not going into the case 1. This is because the ascii value of the character is being stored rather than the character.Could you please rectify this program?
    Thanks,
    vs
    import java.io.*;
    class vowel
    public static void main(String args[])throws Exception
    System.out.println("Enter a character:");
    char ch=(char)System.in.read();
    switch(ch)
    case 1: if(ch=='a')//||ch=='e'||ch=='i'||ch=='o'||ch=='u')
    System.out.println("The character is a vowel-a");
    break;
    default: System.out.println("The character is a consonent ! ");

         ch = Character.toLowerCase(ch);
         switch (ch) {
              case 'a' :
              case 'e' :
              case 'i' :
              case 'o' :
              case 'u' :
                   System.out.println("The character is a vowel: " + ch);
                   break;
              default :
                   System.out.println("The character is a consonent ! ");
         }

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

  • Switch Statement not initializing value

    I'm taking a basic JAVA class and one of our assignments is to use the switch statement to determine the price of a product the add up the total of all products entered at the end. The code below won't compile because it says that "price" isn't initialized. If I initialize the variable as "0.0" then when the program finishes it is still "0.0" which means the switch section isn't working. Can anyone tell me why this isn't working?
    import java.util.Scanner;
    public class Product
    public static void main( String args[] )
         Scanner input = new Scanner(System.in);
         int product;
         int quantity;
         double price;
         double total = 0.0;
         System.out.print("Enter product number: ");
         product = input.nextInt();
         while (product != -1)
              System.out.print("Enter quantity: ");
              quantity = input.nextInt();
              switch (product)
                   case 5:
                        price = 6.87;
                        break;
                   case 4:
                        price = 4.49;
                        break;
                   case 3:
                        price = 9.98;
                        break;
                   case 2:
                        price = 4.50;
                        break;
                   case 1:
                        price = 2.98;
                        break;
                   default:
                        System.out.print("Invalid product number");
                        break;
              total = total + price;
              System.out.println("Enter product number: (-1 to quit)");
              product = input.nextInt();
         System.out.printf("Total retail value of product is: $%.2f", price);
    Thanks for any help!
    Nathan

    I think the correct code should be:
    import java.util.Scanner;
    public class Product
    public static void main( String args[] )
         Scanner input = new Scanner(System.in);
         int product;
         int quantity;
         double price = 0.0;
         double total = 0.0;
         System.out.print("Enter product number: ");
         product = input.nextInt();
         while (product != -1)
              System.out.print("Enter quantity: ");
              quantity = input.nextInt();
              switch (product)
                   case 5:
                        price = 6.87;
                        break;
                   case 4:
                        price = 4.49;
                        break;
                   case 3:
                        price = 9.98;
                        break;
                   case 2:
                        price = 4.50;
                        break;
                   case 1:
                        price = 2.98;
                        break;
                   default:
                        System.out.print("Invalid product number");
                        break;
              total = total + (price*quantity);
              System.out.println("Enter product number: (-1 to quit)");
              product = input.nextInt();
         System.out.printf("Total retail value of product is: $%.2f", total);
    }

Maybe you are looking for