Switch statement trouble in an Applet

Hello everyone. I am attempting to get a Button to work in an applet.
This applet tells and stores jokes. There are two String arrays being used to store the jokes. There are also two buttons being used. (One to tell the jokes - the second to tell the punch line). Coding for this applet is NOT finished, so not all of the components work. However, I am focusing on the "punch line Button".
(Ideally, the punch line should only be reveiled if the joke has already been shown. All jokes and punch lines are stored in two String arrays. I've tried to establish indexes for the joke array and the punch line array so that the user will always get the matching punchline to the joke).
The problem:
The punchline Button will display the first punchline - over and over. I don't understand why. The code is plentiful, here is the snippet of the code for the joke button with the error:
public class Joker3 extends Applet implements ActionListener{
... // the tellJoke Button is not show here because it works okay.
TextArea result;
Button telljoke;
int indexj=0, indexp=0;
String pls[] = new String[10];
public void init(){
result = new TextArea();
punLine = new Button("Punch line");
          punLine.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                    punLine_actionPerformed(e);
   dbase();
public void punLine_actionPerformed(ActionEvent e){
          if(indexp <= pls.length) //Test for end of array
              indexp=0;  //Restart if end is reached
          String str = pls[indexp];
          int i=0;
          if(str == null)
               i=1;
          switch(i){  //checking for null element in array
               case 1: break;
               case 0:{ if(indexp < indexj){  //Only tell joke is told
                             result.append("\n" + pls[indexp]); //only if  indexp == 0 and indexj == 1
                             indexp++; // now both indexp and indexj should be 1
                             str = pls[indexp];  // String variable is updated
                             break;
               break;  //extra break statement to force return of control
public void dbase(){
          jks = new String[20];
          pls = new String[20];
          jks[0]= "Why did the chicken cross the road?";
          jks[1]= "What's the worst thing about working for McDonalds?";
          pls[0]= "To get to the other side.";
          pls[1]= "The pay";
}//end of Applet Thank you in advance for your help.

ha, ha, ha.. well I only put these corny jokes in there to develop the functionality of the Applet. They'll be supplemented with better ones later.
Meanwhile, I just figured out my own error. My problem was within the first if statement:
if(indexp <= pls.length)  // This should have been >=
      indexp = 0;             //  It was resetting idexp to zero each timeThanks to anyone who attempted to answer.

Similar Messages

  • Trouble with  instantiating inherited classes in a switch statement

    Hi
    I have few inherited classes which I need to instantiate in a switch statement based on command line argument supplied by user. I am ble to do that but I cannot access any methods once I come out of the switch scope. Please suggest a way to resolve this problem. The error I am getting is in the end of code in comments // //. Would really appreciate your help.
    Thanks
    Here is the code.
    package assignment2;
    import java.util.*;
    import java.io.*;
    abstract class Parent
    abstract void childclassDescription();
    void generalDescriptionToAllChilds()
    System.out.println("general to all child classes");
    childclassDescription();
    class Child1 extends Parent
    public void childclassDescription()
    System.out.println("i'm child1");
    class Child2 extends Parent
    public void childclassDescription()
    System.out.println("i'm child2");
    class Child3 extends Parent
    public void childclassDescription()
    System.out.println("i'm child3");
    public class Demo
    public static void main(String[] args)
    int option;
    Parent p;
    System.out.println("Pick from one of the following:");
    option=1; // supplying
    switch(option)
    case 1:
    p=new Child1();
    break;
    case 2:
    p=new Child2();
    break;
    case 3:
    p=new Child3();
    default:
    break;
    p.generalDescriptionToAllChilds();
    //error variable p might not have been initialized at line //
    }

    Well I also think that in Java, it is possible for a reference type variable to refer to nothing at all. A reference that refers to nothing at all is called a null reference . By default, an uninitialized reference is null.
    We can explicitly assign the null reference to a variable like this:
    f = null;
    But still i am not quety sure why you needed to do it.

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

  • Switch statement - str and ch comparisons

    Hi everyone,
    As usual lectures are a fat load of good when it comes to explaining anything, can't seem to get this working no matter how much I look over it.
    Basically i'm having trouble looking at a string, determining what is at character three in the string, and then responding by saying what it is (for this I used an if statement in the switch, i'm kinda noob so I can't think of any other way and don't particularly want to change it if it can be helped).
    The only problem i'm getting is it says "char cannot be dereferrenced" and points to this piece of code -- third.equals("a") || third.equals("e") ...and so on.
    I have included the code for you to see...
    thx in advance :)
    /*Program offering users
    *a switch statement choice
    import java.util.*;
    public class Switch
         public static void main (String[] args)
         Scanner kybd = new Scanner(System.in);
         System.out.println("Please enter a string");
         String input = kybd.nextLine();
         System.out.println("---Choose an option---");
         System.out.println("\n" + "1. Work out how many characters the word is");
         System.out.println("2. Display the first character");
         System.out.println("3. Display the last character");
         System.out.println("4. If longer than 3 chracters, is the 3rd a vowel or digit?");
         int choice = kybd.nextInt();
         int length = input.length();
         char third = input.charAt(2);
              switch(choice)
              case 1:
              System.out.println("The length of the phrase is: " + length);
              break;
              case 2:
              char firstLetter = input.charAt(0);
              System.out.println("The first letter is: " + firstLetter);
              break;
              case 3:
              char lastLetter = input.charAt(length-1);
              System.out.println("The last letter is: " + lastLetter);
              break;
              case 4:
              if (third.equals("a"))
              System.out.println("Third character is a vowel: " + third);
              else
                   if (third.equals("0"))
                   System.out.println("Third character is a digit: " + third);
                   else
                   System.out.println("That is neither a vowel or digit");
              break;
              default:
              System.out.println("That is not an acceptable choice");
    }

    Cheers mate, knew it had to be something obvious.
    You would think they would teach us a bit more about ch comparisons before asking us to do it...there's no reference anywhere in lectures to that simple thing.
    Thx for your help.

  • I need some advice on switch statements

    I need to make an applet that accepts 2 things: a product # and how many of a product someone is buying. I have to display the total cost of a product and all the products bought together. My code so far is this:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class store extends Applet implements Actionlistener
         Float runningTotal, overallTotal, howmany;
         TextField txtproductnumber, txthowmany;
         Label lblproductnumber, lblhowmany
         Public void init ()
              lblproductnumber = new Label("Product number:");
              txtproductnumber = new TextField(2);
              add (lblproductnumber);
              add (txtproductnumber);
              lblhowmany = new Label("How many:");
              txthowmany = new TextField(2);
              txthowmany.addActionListener(this);
              add (lblhowmany);
              add (txthowmany);
         public void paint (Graphics g)
              g.drawString ("The total for this purchase is $" + runningtotal, 40, 120);
              g.drawString ("The total for all purchases this session is $" + overalltotal, 40, 140);     
         public void actionPerformed(ActionEvent e)
              productnumber      = Float.valueOf(txtproductnumber.getText());     
              howmany      = Float.valueOf(txthowmany.getText());
         public static void main(string args[])
              switch(runningTotal)
                   Case 1:
                   Case 2:               
                   Case 3:
                   Case 4:
                   Case 5:
    }I got to this point and just froze on what to do next, I'm not even sure if this is going in the right direction... any help appreciated and I have 15 duke dollars assigned to be handed out amongst those who help.
    Thanks!

    Or you can create an int variable say option. Then use an if statement to determine the value of option. Then you can use option in switch statement.
    for example
        if(args[0]=="abcd")
           option=1;
        else
           option=2;
        switch(option){
            case 1:
            case 2:
        }

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

Maybe you are looking for

  • No print to PDF option

    Very recently (after the latest security update?), I've lost the option on the print dialogue to print to a PDF. A work-around is to preview and then save the preview as a PDF, but I would like to have the print to PDF option back. I've run Disk Util

  • I have installed Adobe Flash but firefox does not show as plugin

    I have downloaded the most recent versions of Firefox (30.0) and Adobe Flash Player. The Adobe website tells me my flash player is installed and current but Firefox does not show it as a plug in and a site that requires flash player (google finance)

  • Unsupported Version error when trying to run Web Services Tutorial example

    Hi there, I'm trying to run the first example from the Java Web Services Tutorial and get the following error when I type 'asant build' in my Command Window. Buildfile: build.xml BUILD FAILED java.lang.UnsupportedClassVersionError: com/sun/tools/ws/a

  • How in Discoverer 4i viewer (Web) to set the size of the Chart(Graph)?

    Hello all, How in Discoverer 4i viewer (Web) to set the size of the Chart(Graph) by default? Thanks very much for any help. Dmitriy Zhabrovets

  • Sub: How to send idoc for IW31.

    Dear All, Content: My requirement is to send the idoc for maintanance order- IW31. I found the message type as IORDER. I am not able to use change pointer  IORDER is not matching, as i am not able to find the message type, when executing BD21 (for ch