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

Similar Messages

  • 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

  • Please help a complete noob get started...

    Hi all, new here. I have decided that I would like to be an Oracle DBA. I have always wanted to learn some type of networking, however I admit to being a complete noob to the subject. However, I do have a few really basic questions that I hope I can find some answers to. It may be best if I just number them. (I am in the Dallas/Fort worth Area) Here we go..
    1. What kind of place might a typical oracle DBA work at? A hospital? Or is it more like those giant skyscrapers you see in the city?
    2. How long does it typically take to get certified? This is granted, of course, that you don't fail your classes and have to retake them.
    3. Is there a way I can take the "classes" for the certification online, and possibly test online?
    4. We all get jobs to make money. Being a dad with a family, I have to say that I can't really afford to aim low. What kind of salary might an oracle dba earn?
    5. Is and oracle job something that can be found in some of the smaller towns/suburbs? Or is this something that is kind of scarce?

    user8772743 wrote:
    Well thanks for all the replies guys. Although being such a noob, I have to admit that I did not understand a good portion of them lol. Im pretty computer savvy, but so far I have really been more into hardware. I guess you could call me a hardware enthusiast. I love overclocking and bios modding and gaming.
    But on to my next question. I have noticed, after some searching and looking at some of the links you guys provided, that people in oracle seem to be paid pretty well as a general rule. Just a quick search revealed a few oracle DBA jobs that the starting pay was anywhere from $90k-110K. My question is this: Why does the pay seem to be so much higher than some of the other certifications, such as CCNA? (a cisco cert) Is it because the job is currently in high demand? Just curious I guess. Of course it's part of the reason I want to get into oracle, but i guess im just new... but it still strikes me as strange that there is such a drastic difference between it and some of the other certifications.
    Edited by: user8772743 on Aug 28, 2009 9:14 PMAn employer looking for a DBA will usually be looking for far more than the certification, they'll be looking for evidence of experience, judgement, rigour, responsibility knowledge and a host of other characteristics and an ability to take on new challenges.
    Also a CCNA is an entry level cicso certification, though they do have CCENT which is a little lower. You need to be getting to CCIE to be a little higher.
    From where you are at the moment you might consider a self taught microlight pilot wanting to become an airline pilot on 737s. Would he, after all the training, find that the rigourous and sometimes monotonous drag of a luton to Glasgow shuttle is not really what one wanted.
    I usually like to see little steps first. But you want the big step to the big pay league for iminimum effort ... I guess its possilble ... but ......
    I think because of your current love of hardware you might be better suited to study one the following certifications first
    You may wish to remain with microsoft or whether to get linux experience. I would start with Fedora or Ubuntu, I actually find Ubuntu more fun but less mainstream.
    MSCT
    CCENT (or CCNA)
    LINUX+ or something from CompTIA
    If you want to get into databases and an entry level database certification then a Sun MYSQL CMA is a consideration as an entry level study. Its disdvantages are its unlikely to help you get a job and the SQL syntax is different to Oracle.
    If you can complete before 30th september then a Sun Openoffice Writer Certification is a cheap option (if you can pass it).
    Sometimes looking for evening classes close to where you are might be a better option to channel your efforts on a whats available rather than what I want basis.
    If you are really looking for an online course then try something like: [http://www.ed2go.com/cgi-bin/ed2go/newofferings.cgi?dept=CP] I cannot personnally verify if this particular vendor is useless, bad, cheap or whatever. Some online courses are certainly not to be recomended. Anyway [www.certguard.com] knows about this and while not within certguard remit does not say anything bad about it.
    Quality is probably not great and possibly not up to date but wider width and quite cheap are from [http://www.vtc.com/] .. this is positively cleared at about time of this post by [www.certguard.com] as certification safe. You can look at some lessons here perhaps to decide what you want to get into. If seriously getting into a certification you've be better get something to supplement; but for learning proably okay.
    You can actually do the oracle courses from Oracle online ... but they are quite expensive : [www.oracle.com/education]
    Rgds - bigdelboy.

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

  • 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

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

  • 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

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

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

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

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

Maybe you are looking for

  • What happened to my subscription order?

    HI,  I have purchased 10$ subscription in my account but the status shows it's pending. Moreover it also shows two pending orders of 10$ while I purchased only one. Please explain me what is going to happen next. Is skype going to charge me twice? I

  • Permitted Payee

    Hi I want to create a vendor master with permitted payee..I am tring to find the field in Idoc for permitted payee but there is no field for permitted payee.I dont think we can do using an Idoc extension in this case.Is there any BAPI to create a ven

  • RV110W and QuickVPN - Servers Certificate Doesn't Exist

    After a day of troubleshooting I have finally got the QuickVPN client to work.  I connect however during the connection I get: "Server's certificate doesn't exist on your local computer.  Do you want to quit this connection?" I click no and it connec

  • Installing iTunes to new laptop

    My iPod touch wants me to connect to iTunes before I can access anything on it, but iTunes wants me to plug in my passcode on my iPod. I can't do that, however, because my iPod is not allowing me to do anything until I connect to iTunes, which I can'

  • Crop tool

    My crop tool has suddenly stopped working.  It reduces everything to one pixel.  How can I fix this?