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

Similar Messages

  • 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 for AS3  - Flash CS3

    Hey guys, I currently have a code of a switch statement for as1- as2.
    This is it:
    switch (int(Math.random() * 20))
        case 0:
            hint = "The total amount of confusion in this world remains constant. It just gets shifted around.";
            break;
        case 1:
            hint = "If you experience poor performance, adjust the quality settings in your preference menu option.";
            break;
        case 2:
            hint = "Anticipation of death is better than death itself.";
            break;
        case 3:
            hint = "At the core of all well-founded belief lies belief that is unfounded.";
            break;
        case 4:
            hint = "The problem with instant gratification is that it takes too long.";
            break;
        case 5:
            hint = "Never let your schooling interfere with your education.";
            break;
        case 6:
            hint = "Beware of geeks bearing gifs.";
            break;
        case 7:
            hint = "Collaboration is essential: It allows you to blame someone else.";
            break;
        case 8:
            hint = "Read my MIPs - no new VAXes.";
            break;
        case 9:
            hint = "Where is the sea, said the fish, as they swam through it.";
            break;
        case 10:
            hint = "You can safely blame any bugs on Aoedipus, who is too busy grinding battlegrounds to do QA on her own work.";
            break;
        case 11:
            hint = "Anything worth doing is worth overdoing.";
            break;
        case 12:
            hint = "There is more to life than increasing its speed.";
            break;
        case 13:
            hint = "Don\'t worry, this will take about as long as the time it takes to play a 2v2 match with 4 ret pallies.";
            break;
        case 14:
            hint = "There is nothing worse than the brilliant image of a fuzzy concept.";
            break;
        case 15:
            hint = "If you are not part of the solution, you are part of the precipitate.";
            break;
        case 16:
            hint = "Two wrongs don\'t make a right, but three lefts do.";
            break;
        case 17:
            hint = "The heresy of today is the logic of tomorrow.";
            break;
        case 18:
            hint = "It\'s not that life is so short, it\'s just that you\'re dead a really long time.";
            break;
        case 19:
            hint = "Those who love sausage, the law, and holy canon should never watch any of them being made.";
            break;
        case 20:
            hint = "What if there were no hypothetical questions?";
            break;
    } // End of switch
    hint = "HINT: " + hint;
    This code is for a dynamic tet with the var 'hint' (No ' ' )
    But in as3 there is no var and I am having trouble converting it to AS3 coding, can someone show me the correct conversion of the code to make it work with AS3. I will make the instance name 'hint'.
    Thank you ahead of time.

    In addition to what other guys said, if you still want to use switch it should be:
    switch (Math.round(Math.random() * 20)) - this will cover all the possible integers.
    Nevertheless, I believe using switch in this case is not as efficient and scalable as using, say, array.
    1. array index access is faster than switch.
    2. if you need to make additions, you will need to make additions in switch while with array you just need to add/subtract member
    3. if you will need to switch to a more dynamic model (say, getting hints from xml) - it will not be possible with switch
    4. you may need a greater degree of randmization (Math.random is not as random as one may think) in which case resorting/reordering array is much simpler and faster.
    So, I suggest you switch to the following code:
    var hints:Array = [];
    hints[0] = "Anticipation of death is better than death itself.";
    hints[1] = "Anything worth doing is worth overdoing.";
    hints[2] = "At the core of all well-founded belief lies belief that is unfounded.";
    hints[3] = "Beware of geeks bearing gifs.";
    hints[4] = "Collaboration is essential: It allows you to blame someone else.";
    hints[5] = "Don\'t worry, this will take about as long as the time it takes to play a 2v2 match with 4 ret pallies.";
    hints[6] = "If you are not part of the solution, you are part of the precipitate.";
    hints[7] = "If you experience poor performance, adjust the quality settings in your preference menu option.";
    hints[8] = "It\'s not that life is so short, it\'s just that you\'re dead a really long time.";
    hints[9] = "Never let your schooling interfere with your education.";
    hints[10] = "Read my MIPs - no new VAXes.";
    hints[11] = "The heresy of today is the logic of tomorrow.";
    hints[12] = "The problem with instant gratification is that it takes too long.";
    hints[13] = "The total amount of confusion in this world remains constant. It just gets shifted around.";
    hints[14] = "There is more to life than increasing its speed.";
    hints[15] = "There is nothing worse than the brilliant image of a fuzzy concept.";
    hints[16] = "Those who love sausage, the law, and holy canon should never watch any of them being made.";
    hints[17] = "Two wrongs don\'t make a right, but three lefts do.";
    hints[18] = "What if there were no hypothetical questions?";
    hints[19] = "Where is the sea, said the fish, as they swam through it.";
    hints[20] = "You can safely blame any bugs on Aoedipus, who is too busy grinding battlegrounds to do QA on her own work.";
    hint = hints[int(Math.random() * hints.length)];
    // OR
    hint = hints[Math.round(Math.random() * (hints.length - 1))];

  • How can I use a READ statement for the checking date =sydatum?

    Hello,
         I need use a READ statement on an internal table ITAB (with feild var1) and check whether feild var1<= sydatum(i.e. var1 greater than or equal to sy-datum)....how can I implement this??
    Regards,
    Shashank.

    Hi,
    try this short example.
    DATA: BEGIN OF ITAB OCCURS 0,
            DATE LIKE SY-DATUM,
          END   OF ITAB.
    ITAB-DATE = '20000101'. APPEND ITAB.
    ITAB-DATE = '20010101'. APPEND ITAB.
    ITAB-DATE = '20020101'. APPEND ITAB.
    ITAB-DATE = '20030101'. APPEND ITAB.
    ITAB-DATE = '20040101'. APPEND ITAB.
    ITAB-DATE = '20050101'. APPEND ITAB.
    ITAB-DATE = '20060101'. APPEND ITAB.
    ITAB-DATE = '20070101'. APPEND ITAB.
    ITAB-DATE = SY-DATUM.   APPEND ITAB.
    ITAB-DATE = '20080101'. APPEND ITAB.
    LOOP AT ITAB WHERE DATE < SY-DATUM.
      WRITE: / 'before', ITAB-DATE.
    ENDLOOP.
    LOOP AT ITAB WHERE DATE = SY-DATUM.
      WRITE: / 'equal ', ITAB-DATE.
    ENDLOOP.
    LOOP AT ITAB WHERE DATE > SY-DATUM.
      WRITE: / 'after ', ITAB-DATE.
    ENDLOOP.
    Regards, Dieter

  • Using an output statement for a delete w/o affecting any oracle error msg

    Dear all;
    I have a delete statement similar to this below
      delete from tbl_one t
      where t.tbl_one_location = location
      and location not in (select distinct p.issuearea  from tbl_two p);the delete statement is within a package, however what i would like to do is output a simple message to show if the delete was successful meaning that an actual item was deleted and if it wasnt successful output another statement for that.
    I have an idea in my mind which is to keep track of the number of items in tbl_one before the deletion and then check the count after deletion and if the count is less, then the deletion was successful...hence output the message. Is this the best way to go about it or is there an easier way to do this.
    Thank you, All help is appreciated.

    All u need is this -
    SQL%ROWCOUNTPlease see the folowing -
    SQL> select empno
      2    from emp;
         EMPNO
             1
             2
             3
             4
             5
    SQL>
    SQL> BEGIN
      2     DELETE FROM emp
      3           WHERE empno = 1;
      4 
      5     IF (SQL%ROWCOUNT > 0)
      6     THEN
      7        DBMS_OUTPUT.put_line (SQL%ROWCOUNT || ' Rows Deleted.');
      8     END IF;
      9  END;
    10  /
    1 Rows Deleted.
    PL/SQL procedure successfully completed.
    SQL> select empno from emp;
         EMPNO
             2
             3
             4
             5
    SQL> Hope this helps..
    Formatted the code..
    Edited by: Sri on Mar 22, 2011 8:31 AM

  • Using an NDS statement for a SQL stament run only once in a proceudure

    Hi,
    We're using Oracle 11.1.0.7.0.
    I'm going through code written by someone else. In this package they're using NDS for every SQL call whether it gets called multiple times or just once. Is that a good thing?
    I thought NDS was only reserved for SQL statements that get called over and over again in a procedure with possible varying 'WHERE clause' variables and so on...
    Is there ANY benefit to using NDS for SQL queries called only once in a procedure?
    Thanks

    There is no benefit unless you want to turn PL/SQL into SQL*Plus (parse once, run once)
    Procedures exist to make sure : parse at compile time, run many times.
    The code is shooting itself in its own foot.
    Or the developer must have got hold of Tom Kyte's unpublished one chapter book 'How to write unscalable applications'.
    Sybrand Bakker
    Senior Oracle DBA

  • Using animated character states for web navigation

    Hello everyone, can someone please post some links to Adobe Edge samples that are using character/ personality +small animation+ web navigation. This is just an approximate example I am searching for: a cartoon character is holding a sign, on roll over or on press state the sign expands and shows navigation elements to other pages of the website. Has anything like this has been done using Adobe Edge? I can't even find one example of such interactivity, can you believe this?? I remember when I was heavy into Flash (10 year ago) there was a lots of samples of such web navigation elements, whether they were usability friendly it is another question, but wanted to see if anyone has seen a resent implementation of similar concept online using Adobe Edge. Any assistance is greatly appreciated.

    newguy-
    Have you look on youtube.com ?  I recall a tutorial that had a design, when rolled over did something and then opened to another page (It didn't open a navigation like you are wanting but it could be a start.
    As far as doing something like this in Edge, it should be quite simple to do.  You can set triggers to call other items on the stage; so you could create an animation and on mouseOver, have it expand and call a navigation "symbol" that could appear with all working links.
    Setting the links is easy - I'm working on a site that has the navigation buttons "Appear" from under a design at the beginning of the animation and are linked to seperate pages within the site.
    James

  • Errors when using the Call statement for MS SQL Server

    I've tried executing a Stored Procedure using the Call method of Portal 2 Go. But it gets an internal error b/c of it. Any Ideas why and how to resolve?

    Hello,
    Which version of SAP BOBJ XI3.1 you are using?
    What I am aware is BEGIN_SQL was very well working for SQLServer2005 in case of ODBC connection.
    Can you try one thing for SQLServer2008 have a Native driver installed on your client machine and use ODBC connection rather than OLEDB connection.
    If that works fine, its good
    Otherwise you can raise a message for resolving this problem with the support team.
    Thanks,
    Vivek

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

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

  • 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

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

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

Maybe you are looking for