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

Similar Messages

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

  • Having problem with switch statement..please help

    here my question :
    GUI-based Pay Calculator
    A company pays its employees as executives (who receive a fixed weekly salary) and hourly workers (who receive a fixed hourly salary for the first 40 hours they work in a week, and 1.5 times their hourly wage for overtime worked).
    Each category of employee has its own paycode :
    ?     Paycode 1 for executives
    ?     Paycode 2 for hourly workers
    Write a GUI-based application to compute the weekly pay for each employee. Use switch to compute each employee?s pay based on that employee?s paycode.
    Use CardLayout layout manager to display appropriate GUI components. Obtain the employee name, employee paycode and other necessary facts from the user to calculate the employee?s pay based on the employee paycode:
    ?     For paycode 1, obtain the weekly salary.
    ?     For paycode 2, obtain the hourly salary and the number of hours worked.
    You may obtain other information which you think is necessary from the user.
    Use suitable classes for the GUI elements. (You can use javax.swing package or java.awt package for the GUI elements.)
    here my code so far :
    import java.awt.;*
    import java.awt.event.;*
    import javax.swing.;*
    *public class PayrollSystem implements ItemListener {*
    JPanel cards, JTextField, textField1, JLabel, label1;
    final static String EXECUTIVEPANEL = "1.EXECUTIVE";
    final static String HOURLYPANEL = "2.HOURLY WORKER";
    public void addComponentToPane(Container pane)
    *//Put the JComboBox in a JPanel to get a nicer look.*
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    JPanel userNameAndPasswordPane = new JPanel();
    *// User Name JLabel and JTextField*
    userNameAndPasswordPane.add(new JLabel("NAME"));
    JTextField textField1 = new JTextField(25);
    userNameAndPasswordPane.add(textField1);
    *String comboBoxItems[] = { EXECUTIVEPANEL, HOURLYPANEL };*
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    *//Create the "cards".*
    JPanel card1 = new JPanel();
    card1.add(new JLabel("WEEKLY SALARY"));
    card1.add(new JTextField(6));
    card1.add(new JLabel("TOTAL PAY"));
    card1.add(new JTextField(8));
    card1.add(new JButton("CALCULATE"));
    JPanel card2 = new JPanel();
    card2.add(new JLabel("HOURLY SALARY"));
    card2.add(new JTextField(6));
    card2.add(new JLabel("TOTAL HOURS WORK"));
    card2.add(new JTextField(8));
    card2.add(new JButton("CALCULATE"));
    *//Create the panel that contains the "cards".*
    cards= new JPanel(new CardLayout());
    cards.add(card1, EXECUTIVEPANEL);
    cards.add(card2, HOURLYPANEL);
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(userNameAndPasswordPane, BorderLayout.CENTER);
    pane.add(cards, BorderLayout.PAGE_END);
    public void itemStateChanged(ItemEvent evt)
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    ** GUI created*
    *private static void createAndShowGUI() {*
    *//Make sure we have nice window decorations.*
    JFrame.setDefaultLookAndFeelDecorated(true);
    *//Create and set up the window.*
    JFrame frame = new JFrame("GUI PAY CALCULATOR");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    *//Create and set up the content pane.*
    PayrollSystem demo = new PayrollSystem();
    demo.addComponentToPane(frame.getContentPane());
    *//Display the window.*
    frame.pack();
    frame.setVisible(true);
    *public static void main(String[] args) {*
    *//Schedule a job for the event-dispatching thread:*
    *//creating and showing this application's GUI.*
    *javax.swing.SwingUtilities.invokeLater(new Runnable() {*
    *public void run() {*
    createAndShowGUI();
    HOW CAN I PERFORM THE SWITCH STATEMENT INSIDE THIS CODE TO LET IT FULLY FUNCTIONAL..?
    I MUST PERFORM THE SWITCH STATEMENT LIKE IN THE QUESTION..
    PLEASE HELP ME..REALLY APPRECIATED...TQ

    hi
    A switch works with the byte, short, char, and int primitive data types. So you can simply give the
    switch (month) {
                case 1: 
                            System.out.println("January");
                            break;
                case 2:  {
                            System.out.println("February");
                             break;
                case 3: {
                              System.out.println("March");
                              break;
                             }where month controlls the flow
    moreover u can go to http://www.java-samples.com/java/free_calculator_application_in_java.htm
    for reference, just replace the if statement with switch with correct syntax

  • Switch statement to java string

    Hello!
    I am programing a form in jsp that will send an e-mail to different people , depending on the selection of a SELECT box.
    I am using a Bean which will take the option chosen in the select and then prepare the message.
    My problem is that the option list has a lot of values and I would like to use the switch statement , but I always receive a compilation error since the switch statement only allows int and I am using a String....
    Should I use a nested if in that case...or there is another solution?
    ================
    Form.html
    Region <SELECT NAME="region">
    <OPTION VALUE="SouthEastEurope">South East Europe</OPTION>
    <OPTION VALUE="Italy">Italy</OPTION>
    <OPTION VALUE="SouthernAfrica">Southern Africa</OPTION>
    <OPTION VALUE="France">France</OPTION>
    <OPTION VALUE="NorthernAfrica">Northern Africa</OPTION>
    <OPTION VALUE="MiddleEast">Middle East</OPTION>
    <OPTION VALUE="Iberia">Iberia</OPTION>
    </SELECT><P>....
    ==============================
    SendMail.java
    switch(region)
                        case SouthEastEurope:
                             toAddress = "[email protected]";
                             break;
                        case Italy:
                             toAddress = "[email protected]";
                             break;
    ........and so on.....
                   }

    How about generating a Map to match the country to an address.
    Map mymap = new HashMap();
    mymap.put("SouthEastEurope", "[email protected]");
    mymap.put("Italy", "[email protected]");
    String toadress = (String) mymap.get(region);Saves you from a horrible switch statement.

  • HELP A COMPLETE NOOB! Java Switch Statement?

    Hi, I am trying to use a simple switch statement and I just cant seem to get it to work?;
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    String message;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    message = scan.nextLine();
    int month = 8;
    if (month == 1) {
    System.out.println("January");
    } else if (month == 2) {
    System.out.println("February");
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    Please can anyone help, all I want is to enter a number and the corresponding month to appear. Thank you.

    This will work.
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    // read user input
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    int month = scan.nextInt();
    // print the month
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    }

  • Java Program.. HELP  (switch statement)

    I need help on fixing this program for school.ive looked at information online but i still do not see what i am doing wrong.
    The College Rewards Program is based on a student�s achievements on the ACT Test. Students that have excelled on the test are going to be rewarded for the hard work that they put into high school and studying for the exam. The following are the rewards that will be given to students. They are cumulative, and they get all rewards below their score.
    1. 35-36 $100 a week spending money
    2. 33-34 Free computer
    3. 31-32 $10,000 free room and board
    4. 25-30 $5000 off the years tuition
    5. 21-24 $500 in free books per year
    6. 17-20 Free notebook
    7. 0-16 Sorry, no rewards, please study and try taking the ACT again.
    Make a prompt so the user is asked for their ACT score( be careful).
    Change the ACT score into a number
    Then have the program use that number to display a message about the Rewards program.
    Sample output:
    What was your score on the ACT: 44
    Entry error, please enter a number from 0 to 36.      (error trap wrong numbers)
    What was your score on the ACT: 27
    You got a 27 on the ACT, your rewards are:      ( have it number the rewards)
    1. $5,000 off the year�s tuition
    2. $500 dollars a year in books
    3. A free notebook
    Congratulations on your hard work and good score.
    import java.util.Scanner;
    import java.text.*;
    public class Act
        public static void main (String [] args)
             Scanner scan = new Scanner( System.in );
              int score,reward;
              score=0;
              boolean goodnum;
              do
                      System.out.println( "What was your ACT score? " );
                              score = scan.nextInt() ;
              if (score >0 || score <36) goodnum = true;      
                   else
                    System.out.println ("Please enter the correct number");
                              goodnum=false;     
                    while (score<0 || score>36) {
                              if (score==35 || score==36) reward=1;
                                   else if (score ==34 || score score==33) reward=2;
                                        else if (score==32 || score==31) reward=3;
                                             else if (score>=25 && score<=30) reward=4;
                                                  else if (score>=21 && score<=24) reward=5;
                                                     else if (score>=17 && score<=20) reward=6;
                                                              else reward=7;
        c=0
        switch (reward) {
        case 1: $100 a week spending money
                  c++
                  System.out.println ("$100 a week spending money");     
        case 2:     Free computer
                  c++
                  System.out.println ("Free computer");     
            case 3:      $10,000 free room and board
                  c++
                  System.out.println ("$10,000 free room and board");
        case 4:      $5000 off the years tuition
              c++
              System.out.println ("$5000 off the years tuition");
        case 5:      $500 in free books per year
              c++
               System.out.println ("$500 in free books per year");
        case 6:      Free notebook
              c++
              System.out.println ("Free notebook");
        case 7:      Free notebook
              c++
              System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
              break;
        default:
             System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
            break;
        }

    There are some strange things going on here that could be fixed, so I'll just put my version of how i'd handle this up.
    import java.util.Scanner;
    import java.text.*; // is this really needed? Scanner's the only class I see
    public class Act {
      public static void main( String[] args ) {
        Scanner scan = new Scanner( System.in );
        int score, reward; // don't need to set a value yet
        boolean goodnum;
        do {
          System.out.println( "What was your ACT score? " );
          score = scan.nextInt();
          if ( score >= 0 && score <= 36 ) goodnum = true; // note the && and =s
          else {
            System.out.println( "Please enter a valid number (between 0 and 36)." );
            goodnum = false;
        } while ( !goodnum ); // when this loop finished, the number will be between 0 and 36, a good number
        if ( score >= 35 ) reward = 1;      // save yourself the typing, by now score must be between 0 and 36
        else if ( score >= 33 ) reward = 2; // so just go down with else ifs.
        else if ( score >= 31 ) reward = 3; // this will only reach the lowest point.
        else if ( score >= 25 ) reward = 4;
        else if ( score >= 21 ) reward = 5;
        else if ( score >= 17 ) reward = 6;
        else reward = 7;
        // what was the c for? reward already tells how well they did
        // You handled the switch statement almost perfectly
        // don't break so that reward progressively adds to the output
        if ( reward >= 6 ) { // this if statement is optional, just for good esteem. You could even take it out of the if{}
          System.out.println( "For your score of "+String.valueOf( score )+" you will be rewarded the following:" );
        switch ( reward ) {
          case 1: // $100/week spending money
            System.out.println( "$100 a week spending money." );
          case 2: // Free computer
            System.out.println( "Free computer." );
          case 3: // $10,000 room and board
            System.out.println( "$10,000 free room and board." );
          case 4: // $5000 off tuition
            System.out.println( "$5000 off the year's tuition." );
          case 5: // $500 in free books per year
            System.out.println( "$500 in free books per year." );
          case 6: // Free notebook
            System.out.println( "Free notebook." );
            break; // break here to keep away from discouraging the fine score
          case 7: // since 7 and default are the same result, ignore this and it'll pass to default
          default: // but technically, since reward must be from 1 to 7, default would never explicitly be called
            System.out.println( "Sorry, no rewards. Please study and try taking the ACT again." );
            break; // likely this break is unneccessary
    }That works in my head, hope it works on your computer.

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

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

  • Help With Switch Statements

    Alrighty, so I have to do this assignment for my Java course, using a switch statement. The assignment is to have the user enter a number (1-5), and have the corresponding line of a poem be displayed. So if the user entered 1, "One two, buckle your shoe" would be displayed. This is what I have and it's giving me a huge problem:
    import java.util.Scanner;
    public class Poem
         public static void main(String[] args);
              Scanner kboard = new Scanner(System.in);
              System.out.println("Enter a number 1-5 (or 0 to quit).");
              int n = kboard.nextLine();
              switch (n);
                   case 1: System.out.println("One two, buckle your shoe.");
                   break;
                   case 2: System.out.println("Three four, shut the door.");
                   break;
                   case 3: System.out.println("Five six, pick up sticks.");
                   break;
                   case 4: System.out.println("Seven eight, lay them straight.");
                   break;
                   case 5: System.out.println("Nine ten, a big fat hen.");
                   break;
                   default: System.out.println("Goodbye.");
                   break;
    }This is giving me a HUGE string of errors. (Something like 45). I'm wracking my brain here trying to figure this out. Any help is greatly appreciated. Thanks!

    Well that solved a lot of the errors. Now all I get is this:
    --------------------Configuration: <Default>--------------------
    C:\JavaPrograms\Poem.java:8: <identifier> expected
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:8: illegal start of type
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:12: illegal start of type
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:12: <identifier> expected
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:14: orphaned case
    case 1: System.out.println("One two, buckle your shoe.");
    ^
    C:\JavaPrograms\Poem.java:30: class, interface, or enum expected
    }

  • Help with switch statement

    Hello I have a copy of my code below. Everything compiles fine its just when the code gets to the switch statement I get an error saying
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at Sample.main(Sample.java:55)
    Something is not working right when the user enters an integer expression. what can I do to fix this?
    import java.util.*;
    import java.io.*;
    // Declare a public class
    public class Sample {
         public static void main (String[] args){
         //Declare Variables
         float float0, float1;
         int int0, int1;
         String mathSign;
         char charMathSign;
         Scanner sc = new Scanner(System.in);
         //Ask user to Enter FLoating-Point Number Expression
         System.out.println("Enter a simple floating-point expression: ");
         float0 = sc.nextFloat();
         mathSign = sc.next ();
         float1 = sc.nextFloat();
         if(mathSign.equals("+"))
         System.out.println(float0 + " + " + float1 + " = " + (float0 + float1));     
         else if(mathSign.equals("-"))
         System.out.println(float0 + " - " + float1 + " = " + (float0 - float1));
         else if(mathSign.equals("*"))
         System.out.println(float0 + " * " + float1 + " = " + (float0 * float1));
         else if(mathSign.equals("/"))
         System.out.println(float0 + " / " + float1 + " = " + (float0 / float1));
         //Ask the user to enter a simple floating point expression
         System.out.println("Enter a simple integer expression: ");
         int0 = sc.nextInt ();
         charMathSign = mathSign.charAt(0);
         int1 = sc.nextInt ();
         switch (charMathSign)
              case '+': System.out.println(int0 + " + " + int1 + " = " + (int0 + int1));
              break;
              case '-': System.out.println(int0 + " - " + int1 + " = " + (int0 - int1));
              break;
              case '*': System.out.println(int0 + " * " + int1 + " = " + (int0 * int1));
              break;
              case '/': System.out.println(int0 + " / " + int1 + " = " + (int0 / int1));
              break;
    [/code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    {color:#000080}Duplicate posting, please post all responses at{color}{color:#0000ff}
    http://forum.java.sun.com/thread.jspa?threadID=5219239{color}{color:#000080}
    db{color}

  • Java Switch Statement with Strings

    Apparently you cant make a switch statement with strings in java. What is the most efficient way to rewrite this code to make it function similar to a swtich statement with strings?
    switch (type){
                   case "pounds":
                        type = "weight";
                        break;
                   case "ounces":
                        type = "weight";
                        break;
                   case "grams":
                        type = "weight";
                        break;
                   case "fluid ounces":
                        type = "liquid";
                        break;
                   case "liters":
                        type = "liquid";
                        break;
                   case "gallons":
                        type = "liquid";
                        break;
                   case "cups":
                        type = "liquid";
                        break;
                   case "teaspoons":
                        type = "liquid";
                        break;
                   case "tablespoons":
                        type = "liquid";
                        break;
              }

    I'd create a Map somewhere with entries "liquid", "weight", etc.
    public class Converter {
        private static Map<String, List<String>> unitMap = new HashMap<String, List<String>>();
        private static String[] LIQUID_UNITS = { "pints", "gallons", "quarts", "millilitres" };
        private static String[] WEIGHT_UNITS = { "pounds", "ounces", "grams" };
        static {
            List<String> liquidUnits = new ArrayList<String>();
            for (int i = 0; i < LIQUID_UNITS.length; i++) liquidUnits.add(LIQUID_UNITS));
    unitMap.put("liquid", liquidUnits);
    ... // other unit types here
    public String findUnitType(String unit) {
    for (String unitType : unitMap.keySet()) {
    List<String> unitList = unitMap.get(unitType);
    if (unitList.contains(unit))
    return unitType;
    return null;
    It might not be more "efficient", but it's certainly quite readable, and supports adding new units quite easily. And it's a lot shorter than the series of if/else-ifs that you would have to do otherwise. You'll probably want to include a distinction between imperial/metric units, but maybe you don't need it.
    Brian

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

  • Switch statement help please

    I have been advised on this forum that a switch statement in place of the if else etc would be neater. Could someone tell me where the switch statement goes in the code below.
    Thanks
    Calculator class Calculator.java
    class Calculator {
    public void Calculator() {
    public double workOut(String s1) {
    int count = 0, i_s1_len = 0, i_dot=0, i_neg =0;
    double d_calc=0,d_num = 0, d_snum=0 ;
    String s2 = "", s3 = "", s_num="";
    if (s1.length()==0){ //Check for an input eg contains at least one character
    System.out.println("Sorry you must input a equation ending in an equals '=' sign");
    return 0;
    else {
    i_s1_len = s1.length();
    count = 0; //reset count to zero
    //remove spaces s2 becomes the equation
    for (count=0; count+1 <= i_s1_len;){
    if (s1.charAt(count)==32){
    count++;
    else{
    s2=s2+s1.charAt(count);
    count++;
    i_s1_len = s2.length();//
    // check final character is an "=" sign
    if (s2.endsWith("=")){
    else{
    System .out.println( "Sorry your equation must end with an = sign ");
    return 0;
    // Checking if characters in the equation are legal eg 1-9 or ()-+/*. or the = sign is only at the end.
    count = 0; //reset
    for (count=0; count+1 <= i_s1_len;){
    if ((s2.charAt(count)>39)&(s2.charAt(count)<58)){
    count++;
    else if ((s2.charAt(count)==61) & (count != i_s1_len-1)) {
    System.out.println("Operator'=' is in two places ");
    return 0;
    else{
    count++;
    // Selecting Calculation type +-*/ and calculation Type and conversion
    for (count=0; count+1 <= i_s1_len;){
    //Addition calculation 43 = +
    if (s2.charAt(count)== 43){
    s3="+";
    // Subtraction Calculation 45 = -
    else if (s2.charAt(count)== 45){
    s3="-";
    // check for minus minus
    if (s2.charAt(count+1)== 45){
    s3="+";
    // multiplication Calculation 42 = *
    else if (s2.charAt(count)== 42){
    s3="*";
    // Division Calculation 47 =/
    else if (s2.charAt(count)== 47){
    s3="/";
    //Get String for conversion to number
    else s_num=s_num+s2.charAt(count);{
    count++;
    // Transfer number to single varable
    while ((s2.charAt(count)>47)&(s2.charAt(count)<58)||(s2.charAt(count)==46)){
    s_num=s_num+s2.charAt(count);
    count++;
    //check for multiple decimal points
    if (s2.charAt(count-1)==46){
    i_dot++;
    if (i_dot > 1){
    System.out.println("One of your numbers contains two decimals points ");
    return 0;
    i_dot=0; //reset decimal counter
    // Get opperator + - * /
    if (s3 =="+"){
    d_num = d_num + Double.parseDouble(s_num);
    else if (s3 =="-"){
    d_num = d_num - Double.parseDouble(s_num);
    else if (s3 =="*"){
    d_num = d_num * Double.parseDouble(s_num);
    else if (s3 =="/"){
    if (Double.parseDouble(s_num)==0){
    System.out.println("You are trying to divide by Zero which is infinity");
    return 0;
    d_num = d_num / Double.parseDouble(s_num);
    else{
    d_num = Double.parseDouble(s_num);
    s_num="";
    if (s2.length()==count+1) {
    return d_num;
    return d_num;

    Instead of writing
    if (x == 1)
        // do this
    else if (x == 2)
        // do that
    else
        // do the otheryou can write
    switch (x) {
    case 1:
        // do this
        break;
    case 2:
        // do that
        break;
    default:
        // do the other
        break;
    }

  • Java switch statement

    Is it possible to have a switch statement for multiple values. By this i mean, if a user types in a number between 1-3, it should print out the line
    System.out.println("Well done you got a First");break; So can i have a switch statement which is like
    case 1-3:  System.out.println("Well done you got a First");break;

    This will work:
    case 1:
    case 2:
    case 3:
       System.out.println("Well done you got a First");
    break;No, there's no way to express a "range" in a case statement though.

  • Shortening 'if' statement in Java.

    Hey guys. I'm pretty new to Java and up until now I've never had a problem using if statements. I understand the case statement (switch statement) is available in Java, but this usually involves the input to be a number IIRC.
    That being said, I've got some sample code that maybe somebody could explain how to shorten?
    //FIRST SET
            if (string = "a"){
                object[0].method1();}
            else
                object[0].method2();
            if (string = "b")
                object[0].method3();
            else if (string = "c")
                object[0].method4();
            else
                object[0].method5();
         //SECOND SET
         if (string = "d"){
                object[1].method1();}
            else
                object[1].method2();
            if (string = "e")
                object[1].method3();
            else if string = "f")
                object[1].method4();
            else
                object[1].method5();
            //THIRD SET
            if (string = "g"){
                object[2].method1();}
            else
                object[2].method2();
            if (string = "h")
                object[2].method3();
            else if (string = "i")
                object[2].method4();
            else
                object[2].method5();Basically, it's about 30 lines that I could probably fit into 15 or so if I knew how to shorten it. I think it's fairly straight-forward, but if not, the whole point is that "object" is an array of realistically any number (for the sake of this, it's 3). However, it could also be 2 or 1. Automatically, running this gives an error if 2 or 1 are input (object[2] is out of bounds). The object will respond to a certain input string (I know the if statement is not in correct -- this was just the easier) and will run a method based on that string.
    Anybody know how to shorten this, and make sure that any number of objects in the array can work?
    Thanks for the help.

    LordSleepy wrote:
    LordSleepy wrote:The object will respond to a certain input string (I know the if statement is not in correct -- this was just the easier)I had already explained that. It should have been apparent that it was a sample, it didn't actually do anything, and therefore, the syntax was probably the last thing I needed to correct.I disagree. Your sample should convey what you are trying to do. The code you showed us did nothing at all, because it did not compile.
    If you don't want to care about syntax too much, then better use pseudo-code, such as this:
    if string is "a" then
      call method1
    else
      call method2Here you can use whatever syntax you want, but if your code looks almost like Java code but doesn't compile, then it's a bad example, even if you just want to demonstrate something.
    UPDATE then, I need to take keystrokes (represented here as the strings, although I have a method that responds correctly and does not actually involve strings at all), but I was hoping I could take it from a lot of 'if statements' to something less... drawn out. As you can see, the first "set" is exactly the same as the second and third, except that the object[array] changes from 1 to 2 to 3, and the keystroke varies between a set number of keys. Generally when you have these kind of it-then-else cascades, there's a more object oriented approach that will be a lot cleaner.
    You could, for example, create a Command object for each keystroke (or String in your example) and just put that into a Map indexed by the keystroke/String.
    Command would be a interface with a simple execute() method (optionally providing any context those commands generally need) and your could just fetch the correct Command and call execute().
    This way each class (Command) has a exactly defined task, you can easily add new commands and you get rid of those ugly if-then-else rows.
    An even more general suggestion: If your code looks as if it does the same thing again and again with only slight variations, then you should definitely look into a different design.

Maybe you are looking for

  • How to create a custom protectdoublesubmit window?

    Hi , I am using the xhtmlb:protectdoublesubmit in one BSP page as follows: <xhtmlb:protectDoubleSubmit timer  = "400"                                   active = "TRUE"                                   design = "POPUP"                                

  • Cannot re-install windows 7

    bought a htpc two weeks ago which have runned without any issues until yesterday when i was going to get it out from "sleep mode" i could get and picture via HDMI ... so after restarting the computer liger 100 times i finally got picture but then i c

  • Installation errors for CS6

    Ipourchased and installed CS6 design and web premium after uninstalling the down loaded trial version. I am receiving the following errors: Display requirements not met Error 1310: error writing to file c:\config.msi DF012: File folder does not exist

  • MovieClip pipeline order

    hi, i`ve beeing having problems with pipeline order of movieclip actions, like enterframe, onMouseMove. I would like to sort the pipeline but i can`t find where. I`ve already changed depths but it dosen`t change witch movieclip enterframe goes first.

  • Buying an app as a gift for a friend

    I just got an IPod and a friend has an IPhone. She recently mentioned wanting to get a birding app for her phone. I was wondering, is there any way I can purchase this as a gift for her(I assume with my account)? Best, David