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.

Similar Messages

  • 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

  • Need help in using a case statement in expression operator

    Hi All,
    I am using OWB version 10.2.0.1.0.
    My requirement is to add a new column called call _zone_key in expression operator and map it to the target table. I need to use the below expression for populating call_zone_key values
    Expression:
    case when (INGRP1.CHARGETYPE in ('O','F') or  INGRP1.TARIFF_GROUP in ('SMSINT','MMSINT')or ( INGRP1.CALL_TYPE = '002' and   INGRP1.TARIFF_GROUP  = 'MTV'))
    then
    (select call_zone_reltn_key from call_zone_reltn where
    call_zone_cd=substr(case
      when substr( INGRP1.B_SUBNO,1,2)='00'
      then
      substr( INGRP1.B_SUBNO,3)
      else substr( INGRP1.B_SUBNO,1)
      end,1,length(call_zone_cd))and rownum=1)
    else -1
    end
    All the columns needed for using the above expression is available in INGRP1 but still I am unable to deploy the mapping using above expression. Call_zone_reltn table is also imported to the module. I am getting below error
    Error:
    Warning
    ORA-06550: line 4980, column 2:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
       ( - + case mod new not null others <an identifier>
       <a double-quoted delimited-identifier> <a bind variable> avg
       count current exists max min prior sql stddev sum variance
       execute forall merge time timestamp interval date
       <a string literal with character set specification>
       <a number> <a single-quoted SQL string> pipe
       <an alternatively-quoted string literal with character set specification>
       <an alternativ
    NEW_MOD_MAP_CELL_USAGE_FCT_PRE
    Create
    Warning
    ORA-06550: line 4989, column 43:
    PLS-00103: Encountered the symbol ")" when expecting one of the following:
       * & - + ; / at for mod remainder rem <an exponent (**)> and
       or group having intersect minus order start union where
       connect || multiset
    If i replace the expression with numbers such as 1 or 2, I am able to deploy the mapping.
    Kindly help in fixing this issue.
    Thanks,
    Kabilan

    You can't use the SELECT statement inside the expression, you need to join both tables before the expression. Use a Join operator with this JOIN condition:
    CALCULATED_CALL_ZONE_CD = call_zone_reltn.call_zone_cd ( + )
    Where Calculated_call_zone_cd proceed from a previous expression:
    CALCULATED_CALL_ZONE_CD = substr(case when substr( INGRP1.B_SUBNO,1,2)='00' then substr( INGRP1.B_SUBNO,3) else substr( INGRP1.B_SUBNO,1) end,1,length(call_zone_cd))
    And after joining both tables, you can use another expression to get the rownum, then another filter operator to keep only the rownum = 1, and now you can use your expression without the SELECT, using the call_zone_cd column from the outgroup in the joiner operator (you need to include that column in the filter operator to use it).
    Regards
    ANA GH

  • Use of boolean variables in BPEL switch statements

    I have a workflow with a single boolean input parameter:
    <element name="input" type="boolean"/>
    I wish to use a switch statement within the workflow, based on the value of that boolean parameter.
    When I use the following XPath expression:
    bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")
    I get the correct functionality, although I get the following BPEL compiler warning:
    " [bpelc] [Warning ORABPEL-10078]: return value of this expression may not be a boolean
    [bpelc] [Description]: in line 35 of "C:\eclipse\workspace\Boolean\Boolean.bpel", xpath expression "bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")" used in <switch> may not return boolean type value, the xpath engine would automatically try to convert the return value to boolean..
    [bpelc] [Potential fix]: Please use one of the built-in boolean functions from xpath http://www.w3.org/TR/xpath#section-Boolean-Functions to convert the return value to boolean.."
    However, the boolean functions referenced do not appear to be relevant to a variable which is already of a boolean type. If I attempt to use the boolean() function in my XPath expression, I get rid of the compiler error, but the workflow now does not work as required.
    How can I get rid of the compiler warning and still get the required functionality, and/or am I doing the wrong thing?
    I am currently running on JBoss, with BPEL release 2.1.2 [build #1226].
    Thanks for any help or ideas.

    Hi Marlon,
    Thanks for that - I guess we have to accept the vagaries of XPath and the absence of type-checking for variables.
    I hadn't fully understood until I started investigating that I can assign ANY string to variable of type xsd:boolean, which has been the cause of some of the confusion for me - whether that value is then considered true or false depends on how you write your test condition.
    I tried with your condition, and it didn't seem to work (evaluated to true if the variable data was the string "true()", but otherwise it seemed to always evaluate to false.
    I also tried the following:
    condition="bpws:getVariableData('booleanVariable')=true()"
    but that evaluates to true for any string of length > 0.
    The only one I can get to consistently work is:
    condition="bpws:getVariableData('booleanVariable')=string(true())"
    although that means that variable data of "TRUE" will evaluate to false (may well be the correct behaviour, depending on how you're setting the boolean variable in the first place).

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

  • Compiler error when useing switch statements in an inner class

    I have defined several constants in a class and want to use this constans also in an inner class.
    All the constants are defined as private static final int.
    All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
    What's the difference?
    Look at an example:
    public class Switchtest
       private static final int AA = 0;     
       protected static final int BB = 1;     
       private static int i = 0;
       public Switchtest()
          i = 0; // <- OK
          switch(i)
             case AA: break; //<- OK, funny no problem
             case BB: break; //<- OK
             default: break;
      private class InnerClass
          public InnerClass()
             i = 0; // <- OK: is accessible
             if (AA == i) // <- OK: AA is seen by the inner class; i  is also accessible
                i = AA + 1;
             switch(i)
                case AA: break; // <- STRANGE?! Fail: Constant expression required
                case BB: break; // <- OK
                default: break;
    }Thank's a lot for an explanation.

    Just a though:
    Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final.

  • Static Methods & Switch Statement

    Need help with a switch statement and static methods. My program offers the user a menu to choose what they want to practice.
    I want to use a switch statement to process the selection. Selecting 1, 2 or 3 causes the program to go to one of the following static methods:
    addition()
    subtraction
    multiplication()
    import javax.swing.JOptionPane;  // Needed for JOptionPane
    import java.text.DecimalFormat;  // Needed for DecimalFormat
    public class MathsFinal {
        static boolean exit = false;
        static int totalAnswersAsked = 0;
        public static void main(String[] args)
            int userChoice; 
            int correctAnswers = 0;
            do{
                //custom button text
                do{
                    boolean exitAsking = true;
                    String userChoiceString = JOptionPane.showInputDialog (null,
                            "1. Practice addition\n"
                            + "2. Practice subtraction\n"
                            + "3. Practice multiplication\n"
                            + "4. Quit the program\n"
                            + "\n"
                            + "Enter your choice",
                            "Enter your choice",
                            JOptionPane.QUESTION_MESSAGE);
                    int userAnswer, genNumOne, genNumTwo;
                    if(userChoiceString == null || userChoiceString.equals("4") )
                        { //closed it
                        exit = true;
                    }else if(userChoiceString.equals("1"))
                        { //addition
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne + genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "plus");
                    }else if(userChoiceString.equals("2"))
                        { //subtraction
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(genNumOne,0);
                        userAnswer = genNumOne - genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "minus");
                    }else if(userChoiceString.equals("3"))
                        { //multiplication
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne * genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "times");
                    }else
                        { //user didn't enter a number
                        JOptionPane.showMessageDialog(null,
                                "Please enter a number between 1 and 4",
                                "Wrong entry",
                                JOptionPane.ERROR_MESSAGE);
                        exitAsking = false;
                while(!exit);
            while(!exit);
            //create a DecimalFormat object for percentages.
            DecimalFormat userPercent = new DecimalFormat("#0%");
            //show results using information icon
            JOptionPane.showMessageDialog(null,
                    "You got " + (userPercent.format(((double)correctAnswers / (double)totalAnswersAsked)))  + " right!!",
                    "Thank you for playing",
                    JOptionPane.INFORMATION_MESSAGE);
            //ends the program
            System.exit(0);
        public static int getRandomNumber(int large, int small)
            return  (int)((large - small) * Math.random()) + small;
        public static int display(int genNumOne, int genNumTwo, int userAnswer, String operation)
            String selectAddition = JOptionPane.showInputDialog("What is" + " " + genNumOne + " " + operation + " " + genNumTwo + "?");
            if(selectAddition == null) { //pressed close
                exit = true;
                return 0;
             else if(userAnswer == Integer.parseInt(selectAddition))
              { //answer correct
                totalAnswersAsked++;
                //show results using information icon
                JOptionPane.showMessageDialog(null,
                        "Very good!",
                        "Well done",
                        JOptionPane.INFORMATION_MESSAGE);
                return 1;
             else if(userAnswer != Integer.parseInt(selectAddition))
              { // incorrect answer
                totalAnswersAsked++;
                JOptionPane.showMessageDialog(null,
                        "Sorry that was incorrect. Better luck next time",
                        "Bad luck",
                        JOptionPane.INFORMATION_MESSAGE);
                return 0;
            return 0;
    }

    hi,
    switch statement to process the selection. Selecting 1, 2 or 3
    import javax.swing.JOptionPane;  // Needed for JOptionPane
    import java.text.DecimalFormat;  // Needed for DecimalFormat
    public class MathsFinal {
        static boolean exit = false;
        static int totalAnswersAsked = 0;
        public static void main(String[] args)
            int userChoice; 
            int correctAnswers = 0;
           int userChoiceString=4;
            do{
                //custom button text
                    boolean exitAsking = true;
                    userChoiceString = Integer.parseInt(JOptionPane.showInputDialog (null,
                            "1. Practice addition\n"
                            + "2. Practice subtraction\n"
                            + "3. Practice multiplication\n"
                            + "4. Quit the program\n"
                            + "\n"
                            + "Enter your choice",
                            "Enter your choice",
                            JOptionPane.QUESTION_MESSAGE));
                    int userAnswer, genNumOne, genNumTwo;
                   switch (userChoiceString)
                   case 1:
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne + genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "plus");
                             break;
                        case 2:           
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(genNumOne,0);
                        userAnswer = genNumOne - genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "minus");
                              break;
                        case 3:
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne * genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "times");
                             break;
                        case 4: break;
                     default :
                        JOptionPane.showMessageDialog(null,
                                "Please enter a number between 1 and 4",
                                "Wrong entry",
                                JOptionPane.ERROR_MESSAGE);
                        exitAsking = false;
                } while(userChoiceString != 4);
            //create a DecimalFormat object for percentages.
            DecimalFormat userPercent = new DecimalFormat("#0%");
            //show results using information icon
            JOptionPane.showMessageDialog(null,
                    "You got " + (userPercent.format(((double)correctAnswers / (double)totalAnswersAsked)))  + " right!!",
                    "Thank you for playing",
                    JOptionPane.INFORMATION_MESSAGE);
            //ends the program
            System.exit(0);
        public static int getRandomNumber(int large, int small)
            return  (int)((large - small) * Math.random()) + small;
        public static int display(int genNumOne, int genNumTwo, int userAnswer, String operation)
            String selectAddition = JOptionPane.showInputDialog("What is" + " " + genNumOne + " " + operation + " " + genNumTwo + "?");
            if(selectAddition == null) { //pressed close
                exit = true;
                return 0;
             else if(userAnswer == Integer.parseInt(selectAddition))
              { //answer correct
                totalAnswersAsked++;
                //show results using information icon
                JOptionPane.showMessageDialog(null,
                        "Very good!",
                        "Well done",
                        JOptionPane.INFORMATION_MESSAGE);
                return 1;
             else if(userAnswer != Integer.parseInt(selectAddition))
              { // incorrect answer
                totalAnswersAsked++;
                JOptionPane.showMessageDialog(null,
                        "Sorry that was incorrect. Better luck next time",
                        "Bad luck",
                        JOptionPane.INFORMATION_MESSAGE);
                return 0;
            return 0;

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

  • Switch statement problem

    I am doing a question in which I have to make a simple ATM program that can withraw and deposit money as many times as the user wants. To exit the program the user has to hit "x". I have to use a switch statement. Im getting incompatible type errors after compiling it. Can anyone help me? Sorry if the formattings not too good.
    //ATM.java
    //This program reads in a user's opening balance and performs a withdrawal or a deposit at the request of the user
    import java.text.*;
         public class ATM
         public static void main(String args[])
              int      balance;
              char      withdrawal, deposit, choice;
              //Ask for the opening balance
              System.out.print("Please enter your opening balance");
              balance=UserInput.getInt();
              //Find out what the user wants done
              System.out.print("What would you like to do? (Withdrawal, Depositor Exit(x))");
              choice=UserInput.getChar();
                                                                          switch(choice){     
    case "w":
                                                                          while(balance>0)
                                                                                              System.out.print("How much would you like to withdraw?");
                                                                                              withdrawal=UserInput.getChar();
                                                                                              balance=balance-withdrawal;
                                                                                              System.out.print("Your remaining balance is " + balance);
                                                                                              break;
    case "d":     
    while(balance>0)
                                                                                              System.out.print("How much do you wish to deposit?");
                                                                                              deposit=UserInput.getChar();
                                                                                              balance=balance+deposit;
                                                                                              System.out.print("Your new balance is " + balance);
                                                                                              break;
    case "x":          
                                                                System.out.print("Goodbye and thank you for using this program");
                                                                                              break;
    default:     
                                                                     System.out.print("We were not able to process your request, please try again");
                                                                                              break;
    }

    Type a reply to the topic using the form below. When finished, you can optionally preview your reply by clicking on the "Preview" button. Otherwise, click the "Post" button to submit your message immediately.
    Subject:
    Click for bold      Click for italics      Click for underline           Click for code tags      
      Formatting tips
    Message:
    Add topic to Watchlist:
    Original Message:
    Switch statement problem
    Xivilai Registered: Mar 3, 2007 9:52 AM      Mar 3, 2007 10:06 AM
    I am doing a question in which I have to make a simple ATM program that can withraw and deposit money as many times as the user wants. To exit the program the user has to hit "x". I have to use a switch statement. Im getting incompatible type errors after compiling it. Can anyone help me? Sorry if the formattings not too good.
    //ATM.java
    //This program reads in a user's opening balance and performs a withdrawal or a deposit at the request of the user
    import java.text.*;
    public class ATM
    public static void main(String args[])
    int balance;
    char withdrawal, deposit, choice;
    //Ask for the opening balance
    System.out.print("Please enter your opening balance");
    balance=UserInput.getInt();
    //Find out what the user wants done
    System.out.print("What would you like to do? (Withdrawal, Depositor Exit(x))");
    choice=UserInput.getChar();
    switch(choice){
    case 'w':
    while(balance>0)
    System.out.print("How much would you like to withdraw?");
    withdrawal=UserInput.getChar();
    balance=balance-withdrawal;
    System.out.print("Your remaining balance is " + balance);
    break;
    case 'd':
    while(balance>0)
    System.out.print("How much do you wish to deposit?");
    deposit=UserInput.getChar();
    balance=balance+deposit;
    System.out.print("Your new balance is " + balance);
    break;
    case 'x':
    System.out.print("Goodbye and thank you for using this program");
    break;
    default:
    System.out.print("We were not able to process your request, please try again");
    break;
    }

  • Switch statement & system.read.in

    I am attempting to code a java text program that will calculate and print out 3 different mortgage's, I am trying to use a switch statement to select which mortgages I will output. I am trying a simple switch statement first and I am stuck, Can anyone help.
    //test switch case program
    import java.text.*;
    import java.io.IOException;
    //import java.util.*;
    //import java.lang.*;
    public class TestIfElse
    { // start of main method
    public static void main (String[] args)
              // throws java.io.IOExceptions
    {//start Main
    double interestRate = 0;
    int year;
    double loan;
    char choice;
    //enter # of years & find interest rate
    System.out.println("Enter Years:     7, 15, 30 only:");
    choice = (char) System.in.read(); //System.in.read();
    switch (choice)
    case '1' :     interestRate = 7.25 / 1200;
    System.out.println(+interestRate);
    break;
    case '2' :      interestRate = 8.50 / 1200;
    System.out.println(+interestRate);
                             break;
                   case '3': interestRate = 9.0 / 1200;
    System.out.println(+interestRate);
                             break;
    default : System.out.println("oops");
    }

    ok i couldnt get the switch to work so I tried this and now it wont read in ?? I am about ready to give up. can anybody help??
    //Import the class in the java.text.
    import java.text.*;
    import java.io.IOException;
    //Creates a public class named LarryInterest_f.
    public class larryInterest_f2
    {     //Start of main method using public static class members and void means it does not.
    //return a value,inside main parenthesis is created an array of strings holding arguments.
    public static void main(String[] args) throws IOException
    { //Start Main
    double principal = 200000;//(principal) double (64 bits) string variable created and set to 200000.
    double rate [ ] = {.0535, .055, .0575}; //(rate)double .
    double amount; // (amount) double(64 bit)string variable created.
    double moPay; //(moPay)double(64 bit)string variable created.
    double totalInt; //(64 bit)string variable created.
    int time; //(time) integer (32 bit) variable created and set 1 for total interest.
    int i; // Creates an integer value called i
    int [ ] term = {7,15,30}; // sets the term array of 7,15,30.
    int ratePlace; //pointer
    char answer;
    char totalMo;
    char test;
    char firstIterate;
    char secondIterate;
    System.out.println("What Choice would you Like\n");
    System.out.println("1-Interest rate of 5.35% for 7 years?\n");
    System.out.println("2-Interest rate of 5.55% for 15 years?\n");
    System.out.println("3-Interest rate of 5.75% for 30 years?\n");
    System.out.println("4-Quit\n");
    answer = (char)System.in.read();
    if (answer = 1) {
    ratePlace = 0;
    firstIterate = 4;
    secondIterate = 21;
    totalMo = 84;
    else
    if (answer = 2) {
    ratePlace = 1;
    firstIterate = 8;
    secondIterate = 24;
    totalMo = 180;
    else
    if (answer = 3) {
    ratePlace = 3;
    firstIterate = 15;
    secondIterate = 24;
    totalMo = 360;
    else
    System.out.println("Booga Wooga Chooga");
    amount = (principal + (principal * rate[ratePlace] ));
    moPay = (amount / totalMo);
    totalInt = (principal * rate[ratePlace]);
    dAmount = amount-moPay;
    intPay = totalInt / term[ratePlace];
              // Printout
    DecimalFormat df = new DecimalFormat("#.###,00");
    System.out.println("The Interest on $" + (df.format(principal) + " at" + rate[ratePlace] +"% for a
    loan to be paid off in "+term[ratePlace]+"years is " +"$"+ (df.format(totalInt) +"Dollars\n")));          
    System.out.println("Thek total amount of loan plus interest is $"+(df.formt(amount)+"Dollars.\n"));
    System.out.println("The Payments spread over"+totalMo+"months. would be $"
    +(df.format (moPay) + "Dollars a month for"+term[ratePlace]+"years.\n\n"));
    System.out.println("Would you like to see a payment schedule? y for Yes, or x to Exit");
    test = (char)System.in.read();
    if (test=='y')
    System.out.println("OK Here I Go");
    intPay = (intPay + (totalInt/term[ratePlace]));
    pmt = pmt +1;
    for (int a=1; a<firstIterate; a++){
    System.out.println(" Payment Schedule \n\n");
    System.out.println("Month               Interest                    Balance");
    for (int b=1;b<secondIterate;b++){
    System.out.println(pmt +"\t\t\t\t"+ df.format(intPay) + "\t\t\t"+df.format(dAmount));
    if(pmt <totMO){
    System.out.println(("This Page Complete Press Enter to Continue"));
    System.in.read();

  • 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

  • Editable textbox with text from switch statement.

    I'm trying to make form that has text fields that get pre-populated based upon dropdown choices. I tried to use else/if statements, but I was advised to use a switch statement.  The problem is that I NEED the end-user to be able to make changes to the textbox that is created/generated from the switch statement.  For example I have the code below.  It will switch the text in the textbox perfectly when I choose different items in the AddtlServicesDrop1 box.  But I need the end-user to be able to add more info to the "promotes roots" text....but everytime I type text into the box it disappears when a new cell/item is clicked.  Can anybody give me some help? 
    //Custom Calculate script 
    (function () { 
        var Description1 = getField("AddtlServicesDrop1").value; 
        switch (Description1) { 
        case "Soil Test" : event.value = "To apply the right kind and amount of fertilizer. I need to test your soil. Our soil test will determine pH and nutrient needs (lime, sulfur, phosphorus, & potassium)."; break; 
        case "Heavy Core Aeration": event.value = "Promotes roots"; break; 
        case "Seeding": event.value = "Thin spots"; break; 
        case "Lawn Disease Control Program" : event.value = "Prevent Disease"; break; 
        case "Perimeter Pest Control": event.value = "Prevent Ants"; break; 
        default: event.value = ""; 

    Use equals instead of ==
    String temp = textFieldCountry.getText();
    if (temp .equals("Netherlands"))
    return true;
    else
    return false;

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

  • Switch Statement assistance

    I have to write a program that uses the switch statement and asks the user to select one of three TV models. The programs provides a description of the models. Use the switch statement, display the model chosen, the description and the price.The user should make a selection by model number: The default is "Your choice is not available!"
    I am not 100% sure that I wrote this program correctly with the switch statements and according to the guidelines set forth and would appreciate it if somebody could look it over and see if it looks correct and if not what needs to be addressed. Also, I'm getting an error when I compile (error information at the bottom of the page) and am unsure what needs to be changed to rectify this. Thanks a lot for the guidance.
    import java.util.*;
    import javax.swing.JOptionPane;
    public class javatvmodel {    /**
    * @param args the command line arguments
    static Scanner console = new Scanner (System.in);
        public static void main(String[] args) {        // Declare and initialize variables
    int model = 0;
            String modelString;
            modelString = JOptionPane.showInputDialog("This program asks the user to enter a television model number." + "\n" +
                    "The description of the model chosen will be displayed." + "\n" +
                    "\n" +
                    "Please enter the model number chosen" +"\n" +
                    "Model 100 comes with remote control, timer," + "\n" +
                    "and stereo sound and costs $1000" + "\n" +
                    "Model 200 comes with all the features of Model 100" + "\n" +
                    "and picture-in-picture, and costs $1200" + "\n" +
                    "Model 300 comes with all the features of Model 200 and" + "\n" +
                    "HDTV, flat screen, 16 x 9 aspect ratio and costs $2400");
            switch (model)
                case 100:
                    JOptionPane.showMessageDialog(null,"You chose model 100 with these features:" + "\n" +
                            "remote control, timer, and stereo sound" + "\n" +
                            "Your price will be $1000.00", "Television Selection",JOptionPane.INFORMATION_MESSAGE);
                    break;
                case 200:
                    JOptionPane.showMessageDialog(null,"You chose model 200 TV with these features:" + "\n" +
                            "remote control, timer, stereo sound, and picture-in-picture" + "\n" +
                            "Your price will be $1200.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case 300:
                    JOptionPane.showMessageDialog(null, "You chose model 300 TV with these features:" + "\n" +
                            "remote control, timer, stereo sound, picture-in-picture, HDTV, flat screen, and 16 x 9 aspect ratio" + "\n" +
                            "Your price will be $2400.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
                    break;
                default:
                    JOptionPane.showMessageDialog(null,"Your choice is not available!", JOptionPane.INFORMATION_MESSAGE); }
    Compiling 1 source file to C:\Users\Ryan\Documents\Java\Lab6_Oct7_Moran\JavaTVmodel\build\classes
    C:\Users\Ryan\Documents\Java\Lab6_Oct7_Moran\JavaTVmodel\src\javatvmodel.java:56: cannot find symbol
    symbol : method showMessageDialog(<nulltype>,java.lang.String,int)
    location: class javax.swing.JOptionPane
    JOptionPane.showMessageDialog(null,"Your choice is not available!", JOptionPane.INFORMATION_MESSAGE);
    1 error
    BUILD FAILED (total time: 1 second)
    Edited by: Nightryno on Oct 21, 2008 7:03 PM

    come on now...
    >
    String modelString = "0";
    model = Integer.parseInt(modelString);You haven't shown the input dialog yet! Move the parsing to after you've updated modelString.
    >
    >
    modelString = JOptionPane.showInputDialog("This program asks the user to enter a television model number." + "\n" +
    "The description of the model chosen will be displayed." + "\n" +
    "\n" +
    "Please enter the model number chosen" +"\n" +
    "Model 100 comes with remote control, timer," + "\n" +
    "and stereo sound and costs $1000" + "\n" +
    "Model 200 comes with all the features of Model 100" + "\n" +
    "and picture-in-picture, and costs $1200" + "\n" +
    "Model 300 comes with all the features of Model 200 and" + "\n" +
    "HDTV, flat screen, 16 x 9 aspect ratio and costs $2400");
    switch (model)
    case 100:
    JOptionPane.showMessageDialog(null,"You chose model 100 with these features:" + "\n" +
    "remote control, timer, and stereo sound" + "\n" +
    "Your price will be $1000.00", "Television Selection",JOptionPane.INFORMATION_MESSAGE);
    break;
    case 200:
    JOptionPane.showMessageDialog(null,"You chose model 200 TV with these features:" + "\n" +
    "remote control, timer, stereo sound, and picture-in-picture" + "\n" +
    "Your price will be $1200.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
    break;
    case 300:
    JOptionPane.showMessageDialog(null, "You chose model 300 TV with these features:" + "\n" +
    "remote control, timer, stereo sound, picture-in-picture, HDTV, flat screen, and 16 x 9 aspect ratio" + "\n" +
    "Your price will be $2400.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
    break;
    default:
    JOptionPane.showMessageDialog(null, "Your choice is not available!", "Television Selection", JOptionPane.INFORMATION_MESSAGE);               

Maybe you are looking for