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

Similar Messages

  • Multiple rawValues and switch statements - can you do this?

    Hi, a simple question (i hope)
    first i have to use javascript for his one....
    Im just starting a form and it will have about a dozen dropdown lists (over about 15 pages), each with quite a few variables (i feel a headache coming on already...)
    and what i would like to be able to do is have text fields at the end of the form (hidden) and insert data into them depending on what combination of choices the user has made in some or all of the dropdown lists.
    I know how to get a standard switch statement to work fine but can you (and if so what is the syntax like) do this with multiple lists - and what event would be best to link it to - calculate perhaps?
    the switch would be using stored variables and user entered data to produce composite output to the text field (so case: listA.rawvalue = 1 and listB.rawvalue = nine, and listC.rawvalue = cat etc etc [then] this.rawvalue = v1.value + listB.rawvalue etc.....
    I'm sure you get the issue im struggling with  - I've tried it a few ways but my syntax must be off somewhere
    can anyone assist with the syntax for this kind of thing --or a sample would be fantastic.
    cheers

    Hey Legallogic!
    I'm not 100% certain I understand what you are struggling with but I'd be happy to help.  If you could provide an alternate explanation of your issue I'll take a look and help you solve it.  What I *think* you're asking about is in reference to the test case of a switch statement.  Typically a switch would be used to test the value of one particular variable, so:
    switch (varTest)
         case "A":
              //Do something here
              break;
         case "B":
              //Do something else here
              break;
         default:
              //Do something cool here instead
              break;
    Are you asking how to use a single switch to test the value of multiple variables (or fields)?  If so, my recommendation would be to simply use and if/else if/else block as you can craft your test cases however you'd like for those.
    Like I said, I may not have understood the issue here so feel free to shoot me an email and I'll take a peek!
    Josh Boyle
    Cardinal Solutions Group
    [email protected]

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

  • How to convert switch statement into iif than else statement in SSRS

    Hi All;
    How do i convert switch statement into iif statement in ssrs
    =
    Switch(
    Fields!createdonValue.Value = Now(), "Today",
    Fields!createdonValue.Value = DateAdd("d",-1,Today()),"Yesterday",
    Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -6,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
    Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Week",
    Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -13,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
    Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Fortnight",
    Fields!createdonValue.Value >= DateValue(DateAdd("M",-1,DateAdd("D",-(Day(Now)-1),Now))) and
    Fields!createdonValue.Value <= DateValue(DateAdd("D",-1,DateAdd("D",-(Day(Now)-1),Now))),"Last Month",
    Fields!createdonValue.Value >= DateSerial(Year(Now()), 1, 1) and
    Fields!createdonValue.Value <= DateSerial(Year(Now()), 12, 31),"Year to Date"
    Any help much appreciated
    Thanks
    Pradnya07

    Not sure why you want to se IIF as Switch is more compact
    Anyways it will look like this
    =IIf(
    Fields!createdonValue.Value = Now(), "Today",IIf(
    Fields!createdonValue.Value = DateAdd("d",-1,Today()),"Yesterday",Iif(
    Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -6,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
    Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Week",IIf(
    Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -13,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
    Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Fortnight",IIf(
    Fields!createdonValue.Value >= DateValue(DateAdd("M",-1,DateAdd("D",-(Day(Now)-1),Now))) and
    Fields!createdonValue.Value <= DateValue(DateAdd("D",-1,DateAdd("D",-(Day(Now)-1),Now))),"Last Month",IIf(
    Fields!createdonValue.Value >= DateSerial(Year(Now()), 1, 1) and
    Fields!createdonValue.Value <= DateSerial(Year(Now()), 12, 31),"Year to Date")))))
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

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

  • Enum class not supported for switch() statement in 12.4 beta?

    Hi fellow 12.4 beta testers,
    It would appear "enum class" isn't supported for switch() statements in the 12.4 beta. This compiles fine under clang and g++. Will this be fixed for the final release? This currently causes compile errors for us, since __cplusplus >= 201103L evaluates to true, so our code uses "enum class" instead of plain "enum". It looks like the C++11 standard says it should be supported:
       Switching on enum class in C++ 0x - Stack Overflow
    Many thanks,
    Jonathan.
    $ cat test.cpp
    #include <iostream>
    enum class Ternary { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
    int main( void )
       Ternary foo;
       switch ( foo ) {
          case Ternary::KnownTrue:
          case Ternary::KnownFalse:
          case Ternary::Unknown:
             std::cout << "Success\n";
    $ clang++ -std=c++11 test.cpp
    $ g++ -std=c++11 test.cpp
    $ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -std=c++11 test.cpp
    "test.cpp", line 8: Error: Cannot use Ternary to initialize integral type.
    "test.cpp", line 8: Error: Switch selection expression must be of an integral type.
    "test.cpp", line 9: Error: An integer constant expression is required for a case label.
    "test.cpp", line 10: Error: An integer constant expression is required for a case label.
    "test.cpp", line 11: Error: An integer constant expression is required for a case label.
    5 Error(s) detected.

    Thanks for reporting this problem! I have filed bug 18499900.
    BTW, according to the C++11 standard, the code is actually not valid. Section 6.4.2, switch statement, says an implicit conversion to an integral type is required, which is not the case for for a scoped enum (one using the "class enum" syntax). This limitation was raised in the C++ Committee as an issue to be fixed, and the C++14 standard makes the code valid.
    As a workaround, or to make the code conform to C++11, you can add casts to int for the enum variable and the enumerators.
    Message was edited by: Steve_Clamage

  • Switch Statement again

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

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

  • Switch Statement

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

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

  • 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

  • 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

  • Keyboard Input and switch statement error

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

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

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

  • Problem with switch statement

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

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

  • Switch Statement not initializing value

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

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

Maybe you are looking for

  • How much RAM should my system utilise?

    Hello, Sounds like an odd question and maybe it is, so apologies i am utterly Newbie here. I am running a i7 5930 with 64 gig's of DDR4, typically i am using 70% CPU but the RAM is seldom reaching over 30% usage? Is this odd, am i not applying the so

  • Multiple Routes

    Hi All, Can the route be different for different line items in a sales order? If yes, how is the requested delivery date is getting calculated in this case? Please suggest. Regards, Raghav

  • Consolidating Hierarchy

    Hello, Our requirement: The reporting solution will use the profit center hierarchy-1 for reporting data by profit center.  Financial data(extracted from other system) will be assigned to profit centers in the hierarchy-2.  The only difference betwee

  • Ruby on Rails in Portal Applications?

    how can i make use of Ruby on Rails for developing Portal interfaces

  • I can't export to DivX and XVID files

    Hi all, although I have installed the DivX and XVID Codecs, iMovie 08 (7.1.4) won't show me the Option to export Video with these codecs. If I choose to export with Quicktime, the only options I can choose are: 3G, Apple TV, AVI, Bildsequenz, DV Stre