Static Methods & Switch Statement

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

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

Similar Messages

  • Methods & Switch Statement in java.. HELP!!

    hi all...
    i am having a slight problem as i am constructing a method --> menu() which handles displaying
    menu options on the screen, prompting the user to select A, B, C, D, S or Q... and then returns the user
    input to the main method!!!
    i am having issues with switch statement which processes the return from menu() methd,,,
    could you please help?!!
    here is my code...
    import java.text.*;
    import java.io.*;
    public class StudentDriver
       public static void main(String[] args) throws IOException
          for(;;)
             /* Switch statement for menu manipulation */
             switch(menu())
                   case A: System.out.println("You have selected option A");
                                  break;
                   case B: System.out.println("You have selected option B");
                                  break;
                   case C: System.out.println("You have selected option C");
                                  break;
                   case D: System.out.println("You have selected option D");
                                  break;
                   case S: System.out.println("You have selected option S");
                                  break;
                   case Q: System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                                                                    "\n\n\t\t\t Good Bye \n\n\n\n");
                                  exit(0);    
       static char menu()
          char option;
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));       
          System.out.println("\n\n");
          System.out.println("\n\t\t_________________________");
          System.out.println("\t\t|                       |");
          System.out.println("\t\t| Student Manager Menu  |");
          System.out.println("\t\t|_______________________|");
          System.out.println("\n\t________________________________________");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Add new student\t\t A \t|");
          System.out.println("\t| Add credits\t\t\t B \t|");
          System.out.println("\t| Display one record\t\t C \t|");
          System.out.println("\t| Show the average credits\t D \t|");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Save the changes\t\t S \t|");
          System.out.println("\t| Quit\t\t\t\t Q \t|");
          System.out.println("\t|_______________________________________|\n");
          System.out.print("\t  Your Choice: ");
          option = stdin.readLine();
             return option;
    }Thanking your help in advance...
    yours...
    khalid

    Hi,
    There are few changes which u need to make for making ur code work.
    1) In main method, in switch case change case A: to case 'A':
    Characters should be represented in single quotes.
    2) in case 'Q' change exit(0) to System.exit(0);
    3) The method static char menu() { should be changed to static char menu() throws IOException   {
    4) Change option = stdin.readLine(); to
    option = (char)stdin.read();
    Then compile and run ur code. This will work.
    Or else just copy the below code
    import java.text.*;
    import java.io.*;
    public class StudentDriver{
         public static void main(String[] args) throws IOException {
              for(;;) {
                   /* Switch statement for menu manipulation */
                   switch(menu()) {
                        case 'A': System.out.println("You have selected option A");
                        break;
                        case 'B': System.out.println("You have selected option B");
                        break;
                        case 'C': System.out.println("You have selected option C");
                        break;
                        case 'D': System.out.println("You have selected option D");
                        break;
                        case 'S': System.out.println("You have selected option S");
                        break;
                        case 'Q':
                        System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                        "\n\n\t\t\t Good Bye \n\n\n\n");
                        System.exit(0);
         static char menu() throws IOException {
              char option;
              BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("\n\n");
              System.out.println("\n\t\t_________________________");
              System.out.println("\t\t| |");
              System.out.println("\t\t| Student Manager Menu |");
              System.out.println("\t\t|_______________________|");
              System.out.println("\n\t________________________________________");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Add new student\t\t A \t|");
              System.out.println("\t| Add credits\t\t\t B \t|");
              System.out.println("\t| Display one record\t\t C \t|");
              System.out.println("\t| Show the average credits\t D \t|");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Save the changes\t\t S \t|");
              System.out.println("\t| Quit\t\t\t\t Q \t|");
              System.out.println("\t|_______________________________________|\n");
              System.out.print("\t Your Choice: ");
              option = (char)stdin.read();
              return option;
    regards
    Karthik

  • 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

  • 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 & system.read.in

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

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

  • Switch statement help!!

    ive not done switch statements before, i have a list of months and i have a number from another method which i need to use in this switch statement to obtain the right month.
    example is that the other method returns me with the number 4.....this should give me the month april =D
    im not sure where to go with this.....
    private static String getMonthName(String[] args)
            switch (month)
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
            }

    Either you can do this
          private static String getMonthName(String[] args)
            month=getMonthIndex();
            switch (month)
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
    or this
          private static String getMonthName(String[] args)
            switch (getMonthIndex())
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
                  Assuming that you have a method which returns an index representing a month which in this case i have assumed as getMonthIndex( )

  • Problem with switch-statement & ä, ö, ü

    Hi all,
    I am doing this Java online tutorial right now and have a problem with one of the exercises. Hopefully you can help me:
    I have to write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line. I found a solution, but have two questions about it:
    •     I’m unable to calculate the amount of umlauts (ä, ö, ü). Somehow the program doesn’t recognize those characters. Why?
    •     In general I’m not very happy with this huge list of “cases”. How would you solve a problem like this? Is there a more convenient/elegant way?
    Thanks in advance!
    Write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line.
    Read in the line into a String (in the usual way). Now use the charAt() method in a loop to access the characters one by one.
    Use a switch statement to increment the appropriate variables based on the current character. After processing the line, print out
    the results.
    import java.util.Scanner;
    class Kap43A1
      public static void main ( String[] args )
        String line;
        char letter;
        int total, countV=0, countC=0, countS=0, countU=0, countP=0;
        Scanner scan = new Scanner(System.in);
        System.out.println( "Please write a sentence " );
        line = scan.nextLine();
        total=line.length(); //Gesamtanzahl an Zeichen des Satzes
        for (int counter=0; counter<total; counter++)
          letter = line.charAt(counter); //ermitteln des Buchstabens an einer bestimmten Position des Satzes
          switch (letter)
            case 'A': case 'a':
            case 'E': case 'e':
            case 'I': case 'i':
            case 'O': case 'o':
            case 'U': case 'u':
              countV++;
              break;
            case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h':
            case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'P': case 'p':
            case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'V': case 'v': case 'W': case 'w':
            case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z':
              countC++;
              break;
            case ' ':
              countS++;
              break;
            case ',': case '.': case ':': case '!': case '?':
              countP++;
              break;
            case 'Ä': case 'ä': case 'Ö': case 'ö': case 'Ü': case 'ü':
              countU++;
              break;
        System.out.println( "Total amount of characters:\t" + total );
        System.out.println( "Number of consonants:\t\t" + countC );
        System.out.println( "Number of vocals:\t\t" + countV );
        System.out.println( "Number of umlauts:\t\t" + countU );
        System.out.println( "Number of spaces:\t\t" + countS );
        System.out.println( "Number of punctuation chars:\t" + countP );
    }

    WRE wrote:
    •In general I’m not very happy with this huge list of “cases”. How would you solve a problem like this? Is there a more convenient/elegant way?I've been doing this a lot lately myself evaluating documents with 20 or so million words. Few tips:
    1. Regular expressions can vastly reduce the list of cases. For example you can capture all letters from a to z or A to Z as follows [a-zA-Z]. To match a single character in a String you can then make use of the Pattern and Matcher classes, and incorporate the regular expression. e.g.
      //Un-compiled code, may contain errors.
      private Pattern letterPattern = Pattern.compile("[a-zA-Z]");
      public int countNumberOfLettersInString(final String string) {
        int count = 0;
        Matcher letterMatcher = letterPattern.matcher(string);
        while(letterMatcher.find()) {
          count++;
        return count;
      }2. As mentioned above, Sets are an excellent choice. Simply declare a static variable and instantiate it using a static initializer block. Then loop over the String to determine if the character is in the given set. e.g.
      //Un-compiled code, may contain errors.
      private static Set<Character> macrons = new HashSet<Character>();
      static {
        macrons.add('ä');
        macrons.add('ö');
        macrons.add('ü');
      public int countNumberOfMacronsInString(final String string) {
        int count = 0;
        for(char c : string.toCharArray()) {
          if(macrons.contains(c) {
            count++;
        return count;
      }Mel

  • Help with Switch statements using Enums?

    Hello, i need help with writing switch statements involving enums. Researched a lot but still cant find desired answer so going to ask here. Ok i'll cut story short.
    Im writing a calculator program. The main problem is writing code for controlling the engine of calculator which sequences of sum actions.
    I have enum class on itself. Atm i think thats ok. I have another class - the engine which does the work.
    I planned to have a switch statement which takes in parameter of a string n. This string n is received from the user interface when users press a button say; "1 + 2 = " which each time n should be "1", "+", "2" and "=" respectively.
    My algorithm would be as follows checking if its a operator(+) a case carry out adding etc.. each case producing its own task. ( I know i can do it with many simple if..else but that is bad programming technique hence im not going down that route) So here the problem arises - i cant get the switch to successfully complete its task... How about look at my code to understand it better.
    I have posted below all the relevant code i got so far, not including the swing codes because they are not needed here...
    ValidOperators v;
    public Calculator_Engine(ValidOperators v){
              stack = new Stack(20);
              //The creation of the stack...
              this.v = v;          
    public void main_Engine(String n){
           ValidOperators v = ValidOperators.numbers;
                    *vo = vo.valueOf(n);*
         switch(v){
         case Add: add();  break;
         case Sub: sub(); break;
         case Mul: Mul(); break;
         case Div: Div(); break;
         case Eq:sum = stack.sPop(); System.out.println("Sum= " + sum);
         default: double number = Integer.parseInt(n);
                       numberPressed(number);
                       break;
                      //default meaning its number so pass it to a method to do a job
    public enum ValidOperators {
         Add("+"), Sub("-"), Mul("X"), Div("/"),
         Eq("="), Numbers("?"); }
         Notes*
    It gives out error: "No enum const class ValidOperators.+" when i press button +.
    It has nothing to do with listeners as it highlighted the error is coming from the line:switch(v){
    I think i know where the problem is.. the line "vo = vo.valueOf(n);"
    This line gets the string and store the enum as that value instead of Add, Sub etc... So how would i solve the problem?
    But.. I dont know how to fix it. ANy help would be good
    Need more info please ask!
    Thanks in advance.

    demo:
    import java.util.*;
    public class EnumExample {
        enum E {
            STAR("*"), HASH("#");
            private String symbol;
            private static Map<String, E> map = new HashMap<String, E>();
            static {
                put(STAR);
                put(HASH);
            public String getSymbol() {
                return symbol;
            private E(String symbol) {
                this.symbol = symbol;
            private static void put(E e) {
                map.put(e.getSymbol(), e);
            public static E parse(String symbol) {
                return map.get(symbol);
        public static void main(String[] args) {
            System.out.println(E.valueOf("STAR")); //succeeds
            System.out.println(E.parse("*")); //succeeds
            System.out.println(E.parse("STAR")); //fails: null
            System.out.println(E.valueOf("*")); //fails: IllegalArgumentException
    }

  • Default case not working in a switch statement

    I get a run-time error when i input other flavor than the three listed in the code.
    Any comments and suggestions are welcomed.
    import java.util.Scanner;
    public class EnumSwitchDemo
         enum Flavor {VANILLA, CHOCOLATE, STRAWBERRY};
         public static void main(String[] args)
              Flavor favorite = null;
              Scanner keyboard = new Scanner(System.in);
              System.out.println("What is your favorite flavor? ");
              String answer = keyboard.next();
              answer = answer.toUpperCase();
              favorite = Flavor.valueOf(answer);          
              switch(favorite)
                   case VANILLA:
                        System.out.println("Classic");
                        break;
                   case CHOCOLATE:
                        System.out.println("Rich");
                        break;
                   case STRAWBERRY:
                        System.out.println("Tasty");
                        break;
                   default:
                        System.out.println("Sorry, Flavor unavailable");
                        break;
    }

    Yes, the static valueOf method of an Enum type throws an IllegalArgumentException, if the name is not defined, I think. So the problem is not the switch statement.
    Btw, normally you don't need switch statements with enums, since you can define methods in enums.
    -Puce

  • *********H E L P*********with SWITCH STATEMENT

    I am creating a class that extends object. I am using JOptionPane for input. I have a switch statement that I am using to call other methods, such as displaying a flag using GraphicsPen. Everything works great except when the switch calls the flag method and displays the flag, I can't close the flag until I end the switch method. I have a " for(;;) " statement that encloses the main method so the switch method will continue after each iteration.*********HELP*********PLEASE!*****************

    class switchflags extends Object //class declaration
    public static void main (String[]args) //main method
    final String TITLE = "SWITCH"; //title for dialogs
    for (;;) //loop
    String switchstring = JOptionPane.showInputDialog //dialog for input
    (null,"Select which program you want to use from below.\n\n"+
    "*******Press enter when finished*******\n\n"+
    "Enter 0 : to Quit\n"+
    "Enter 1 : to see the Dutch Flag\n"+
    "Enter 2 : to see the Mauritius Flag\n"+
    "Enter 3 : to see the Italian Flag\n"+
    "Enter 4 : to see the Norwegian Flag\n"+
    "Enter 5 : to calculate Fibonacci number (n)\n"+
    "Enter 6 : to calculate Miles Per Gallon\n\n",TITLE,JOptionPane.INFORMATION_MESSAGE);
    int switchint = Integer.parseInt(switchstring); //convert string to a integer
    if (switchint == 0) //exit if 0 was entered
    JOptionPane.showMessageDialog
    (null,"Thanks for using this program.\nHave a nice day!",TITLE,JOptionPane.PLAIN_MESSAGE);
    System.exit(0); //end program
    else if (switchint < 0) //show error for invalid numbers less than zero
    JOptionPane.showMessageDialog
    (null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
    TITLE,JOptionPane.ERROR_MESSAGE);
    else if (switchint > 6) //show error for invalid numbers greater than six
    JOptionPane.showMessageDialog
    (null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
    TITLE,JOptionPane.ERROR_MESSAGE);
    switch (switchint) //test variable that was entered
    case 1: DutchFlag1.start(); //display Dutch flag
    break;
    case 2: mauritius.start(); //display Mauritius flag
    break;
    case 3: italy.start(); //display Italy flag
    break;
    case 4: norway.start(); //display Norway flag
    break;
    case 5: FIBONACCI.start(); //run Fibonacci program
    break;
    case 6: MPG.start(); //run MPG program
    break;

  • Switch statement and case variables

    Since constant variables do not have to be initialized when declared, they could be initialized later based on conditional logic and used to make the Switch statement more useful by using them as case labels. Well, sounds good in theory but I can't find anyway to make it work.
    I can't even get this to compile when the value of the case label is obvious at compile time :
    public class Switchtest
    public static void main(String[] args)
    int test = 0;
    final int x;
    x = 1;
    switch (test)
    case x: System.out.println("case x " );break;
    default: System.out.println("Default ");break;
    It gives an error about expecting x to be constant. I've tried static initializer blocks, etc. Is there anyway to have the case label variables initialized at runtime to make the Switch statement more useful?

    If jvm can use a hashtable for a switch statement. This hashtable is as constant as the compiled code, i.e., it can be defined at compile- time and it con not be modified runtime. Therefore a switch- case construction is faster than an else-if construction. But the strength of else- if is that it is more flexible. If you want to test on multiple variable values, you must use else-if
    class a
       public int method()
          int val = (int)(Math.random()*3);
          int x;
          if(val == 0)
             x = 1;
          else if(val == 1)
             x = 2;
          else
             x = 3;
          return x;
    class b
       public int method()
          int val = (int)(Math.random()*3);
          int x;
          switch (val)
             case 0:
                x = 1;
                break;
             case 1:
                x = 2;
                break;
             default:
                x = 3;
                break;
          return x;
    }b is bigger than a, but also faster. The technique used in a is more flexible, but b uses O(1) time where a uses O(n). (where n is the number of cases/else-ifs)

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

  • Optimizing sparce switch statements

    While taking over some code I stumbled across the following
    int rotation;
    switch (rotation) {
    case 0:
        break;
    case 90:
        g.translate(-w, 0);
        break;
    case 180:
        g.translate(-w, -h);
        break;
    case 270:
        g.translate(0, -h);
        break;
    }Does the Java compiler generate a jump table with O(270) entries, or does it optimized this by converting it to
    if (rotation == 90)
        g.translate(-w, 0);
    else if (rotation == 180)
        g.translate(-w, -h);
    else if (rotation == 270)
        g.translate(0, -h);I've seen compilers for other languages that convert sparce switch statements to if, else ifs, and I was wondering what the SDK Java does.

    Compiled from Switch.java
    class Switch extends java.lang.Object {
        Switch();
        public static void main(java.lang.String[]);
    Method Switch()
       0 aload_0
       1 invokespecial #1 <Method java.lang.Object()>
       4 return
    Method void main(java.lang.String[])
       0 sipush 180
       3 istore_1
       4 iconst_0
       5 istore_2
       6 iload_1
       7 lookupswitch 4: default=68
             0: 48
            90: 51
           180: 57
           270: 64
      48 goto 68
      51 bipush 90
      53 istore_2
      54 goto 68
      57 sipush 180
      60 istore_2
      61 goto 68
      64 sipush 270
      67 istore_2
      68 returnNot being intimately familar with Java byte-codes, it appears that lookupswitch is some kind of JVM operation that performs a search (effectively if, else if). Is tableswitch another JVM operation that does a table lookup? What kind of code generates tableswitch?

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

Maybe you are looking for

  • Some videos not showing up on AppleTV from iMac's iTunes library

    Having a strange problem. Not sure if it is an iTunes problem or an AppleTV problem but I will try here first. I have several videos in my library, some of which are digitized home videos I edited/rendered, others are AppleTV converted DVD's I own. F

  • On Board Audio Output Noise...

    After reading several posts, and making adjustments throughout Win2K, I have yet to get rid of the continual static noise which fluctuates in intensity depending on hard drive and general system activity. I have no IRQ or resource conflicts to do wit

  • No songs now in i-tunes library but all still on i pod

    help dont know what has happened cant play any songs on i tunes, all still on i pod. on i tunes still has song names but most with ! beside it. i cant locate these songs as they are empty. any help or suggestions would be appreciated thansk pter

  • Iphoto play video jumpy

    Why in  iphoto videos play back jumpy when I drag video to decktop video play find on quicktime.

  • Multifunction laser printer recommendations

    I'm looking for recommendations for a multifunction laser printer (print/copy/scan), color or monochrome that works well with the Imac 24. Any suggestions? Thanks!