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

Similar Messages

  • Switch statement with JRadioButton!!!

    hi there guys....
    Good day/!
    can anyone give me some short example on switch statements with JRadioButton???

    * Radio_Test.java
    package basics;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Radio_Test extends JFrame implements ActionListener{
        public Radio_Test() {
            setTitle("Radio Test");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            buttonGroup1 = new ButtonGroup();
            toolbar = new JToolBar();
            btn1 = new JRadioButton("btn1");
            btn2 = new JRadioButton("btn2");
            btn3 = new JRadioButton("btn3");
            btn4 = new JRadioButton("btn4");
            //init button 1
            buttonGroup1.add(btn1);
            btn1.setActionCommand("1");
            btn1.addActionListener(this);
            toolbar.add(btn1);
            //init button 2
            buttonGroup1.add(btn2);
            btn2.setActionCommand("2");
            btn2.addActionListener(this);
            toolbar.add(btn2);
            //init button 3
            //init button 4
            getContentPane().add(toolbar, BorderLayout.NORTH);
            pack();
        public void actionPerformed(final ActionEvent e) {
            JRadioButton source = (JRadioButton)e.getSource();
            int action = Integer.parseInt(source.getActionCommand());
            showStatus(action);
        private void showStatus(final int action){
            switch(action){
                case 1:
                    JOptionPane.showMessageDialog(this, "Choice was 1");
                    break;
                case 2:
                    JOptionPane.showMessageDialog(this, "Choice was 2");
                    break;
                case 3:
                    JOptionPane.showMessageDialog(this, "Choice was 3");
                    break;
                default:
                    JOptionPane.showMessageDialog(this, "Choice must be 1, 2, or 3");
        public static void main(final String args[]) { new Radio_Test().setVisible(true); }
        private ButtonGroup buttonGroup1;
        private JRadioButton btn1,btn2,btn3,btn4;
        private JToolBar toolbar;
    }

  • Beginner question regarding switch statements with arrays....

    Doing a little project for my beginner's object oriented programming course. I've written the following code, but the switch statement won't recognize my array values....I'm required to use a switch statement in my program, which will count various character types in an external file....any insight is appreciated.
    import java.io.*;
    public class MyProg
      public static BufferedReader inFile;
      public static void main(String[] args)
        throws IOException, StringIndexOutOfBoundsException
        String line;
        inFile = new BufferedReader(new FileReader("TME5Part1.dat3"));
          char UpperCase[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M',
                                          'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};          
          char LowerCase[]=     {'a','b','c','d','e','f','g','h','i','j','k','l','m',
                                          'n','o','p','q','r','s','t','u','v','w','x','y','z'};
          char Digit[]= {'0','1','2','3','4','5','6','7','8','9'};
          char EndMark[]= {'!','.','?'};
          char MidMark[]= {',',':',';'};
        char symbol;                                                            
        int upperCaseCt = 0;                                             
        int lowerCaseCt = 0;
        int digitCt = 0;
        int endMarkCt = 0;
        int midMarkCt = 0;
          int spaceCt = 0;
          int otherCharCt = 0;
        line = inFile.readLine();          //read first line (priming read)
        while (line != null)               // Loop until end of data (empty line)
          for (int count = 0; count < line.length(); count++)  // Loop until end of line
            symbol = line.charAt(count);                    
                for (int i=0; i<=25;i++)                              
                        char uppercase=UpperCase;               //get array values for i
                        char lowercase=LowerCase[i];
                        if (i<=9) {char digit=Digit[i];}               
                        if (i<=2) {     char endmark=EndMark[i];     
                                            char midmark=MidMark[i];
                        switch(symbol)                                             
                                  case uppercase : upperCaseCt++;
                                            break;
                                  case lowercase : lowerCaseCt++;
                                                 break;
                                  case digit          : digitCt++;
                                                 break;
                                  case endmark     : endMarkCt++;
                                                 break;
                                  case midmark     : midMarkCt++;
                                                 break;
                                  case ' '          : spaceCt++;
                                                 break;
                                  default          : otherCharCt++;
                                                 break;
              line = inFile.readLine();                                   
         System.out.println("Number of uppercase letters = "+upperCaseCt);               
         System.out.println("Number of lowercase letters = "+lowerCaseCt);
         System.out.println("Nubmer of digits = "+digitCt);
         System.out.println("Number of end punctuation marks = "+endMarkCt);
         System.out.println("Number of mid punctuation marks = "+midMarkCt);
         System.out.println("Number of spaces = "+spaceCt);
         System.out.println("Number of other characters = "+otherCharCt);
    I was trying to do it this way rather than "case 'A':
    case 'B':
    case 'Z:" for each type of 'symbol'.
    Unfortunately, the switch statement is required or this would be easier with arrays and for loops...I'm not sure if my code is even possible. Thanks in advance =)
    Edited by: RiTarDid

    RiTarDid wrote:
    For sure it is the most straightforward way, but my curiosity is getting the better of me....I will most likely submit the program with the longer (value-by-value) switch method, as I haven't found anyone who can tell me how to properly reference an array value in a 'case'.Well, you can do this (basically):
    switch(some_array[some_index]) {
        case 'a':  blahblah
        case 'z':  blahblah
    }What you can't do is this:
    switch(some_scalar_value) {
      case a_whole_array:  blahblah
      case a_whole_another_array: blahblah
    }Because the latter isn't what "case" means.
    If you want to do something like the latter, use if/else statements. Here's a dirty little industry secret: people seldom use switch/case. if/else is a lot more common.
    Actually that dirty little secret isn't really particular dirty or particularly secret. It is, however, little.
    I just recall a suggestion to use arrays for any group that is more than 10 values in size;Well...sort of...
    You should use the expression of data that's appropriate for what the data is. If it's a collection of data of the same kind and an ordering, then an array or a java.util.List makes sense. If it's data that is of the same kind but no ordering and no duplicates are allowed, use a java.util.Set. (Etc. on this front.) If it's a collection of un-alike data, but which belongs in associated groups (e.g., a user's name, age, height, and whether s/he's married) then you should create a class that represents that logical grouping. Etc. If you have more than 10 individual data that can't be grouped or collected somehow, then chances are you need to rethink what's happening.
    so I wanted to see if an array could be employed for comparisons with the 'switch' statement. The program is simple enough, I'm just trying to flex my problem-solving muscle in different ways. :)
    thanks for replying, hope I can get a definite "yes, it can be done this way" or "no it can't" if there's anyone out there who knows.....The problem is that your example is contrived. So you can do a variety of things that fit into the contrivance, but they'd be weird things.
    In practice, you'd want to use the character classification methods in Character, if you wanted to characterize a bunch of characters. Or maybe a regular expression. There's no need to keep an array of characters to match against if you want to determine whether a particular character is upper case. In fact, that's the wrong way of doing things, because Character.isUpperCase is more likely to tell whether any character (not just stuff that's also an element of ASCII) qualifies as upper case.

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

  • Switch statement with println() for enum

    Hi,
    I have this exercise maybe you could help with:
    I have to create an enum class and then print out a description of each of the values from a switch.
    This is what I've done..
    enum PaperCurrency {
         FIVE, TEN, TWENTY, FIFTY, ONE_HUNDRED, TWO_HUNDRED
    public class Ex22 {
         PaperCurrency amount;
         Ex22(PaperCurrency amount) {
              this.amount = amount;
         void describe() {
              switch(amount) {
              case FIVE:               System.out.println("five dollar note");
              case TEN:               System.out.println("ten dollar note");
              case TWENTY:          System.out.println("twenty dollar note");
              case FIFTY:               System.out.println("fifty dollar note");
              case ONE_HUNDRED:     System.out.println("a hundred dollar note");
              case TWO_HUNDRED:     System.out.println("two hundred dollar note");
    static void main(String[] args) {
              Ex22
                   fiveDollars = new Ex22(PaperCurrency.FIVE),
                   tenDollars = new Ex22(PaperCurrency.TEN),
                   twentyDollars = new Ex22(PaperCurrency.TWENTY),
                   fiftyDollars = new Ex22 (PaperCurrency.FIFTY),
                   aHundredDollars = new Ex22 (PaperCurrency.ONE_HUNDRED),
                   twoHundredDollars = new Ex22 (PaperCurrency.TWO_HUNDRED);
              fiveDollars.describe();     
    }There are no compilation errors.
    The print out on the console is like this for fiveDollars.describe():
    five dollar note
    ten dollar note
    twenty dollar note
    fifty dollar note
    a hundred dollar note
    two hundred dollar note
    and it is supposed to be:
    five dollar note.
    My question is how to only print out the relevant description instead of all of them? Is my switch wrong?
    Thanks for any help

    If you can, it makes more sense to add functionality to an enum type than to write switch statements:
    public enum PaperCurrency {
        FIVE("five dollar note"),
        TEN("ten dollar note"),
        TWENTY("twenty dollar note"),
        FIFTY("fifty dollar note"),
        ONE_HUNDRED("one hundred dollar note"),
        TWO_HUNDRED("two hundred dollar note");
        private String description;
        private PaperCurrency(String desc) {
            description = desc;
        public String getDescription() {
            return description;
        public static void main(String[] args) {
            System.out.println(PaperCurrency.TEN.getDescription());
    }

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

  • Switch statement with enumerated types

    Hello,
    I'm currently having problems (error in eclipse) using enums in a
    switch block. Eclipse says:
    "The enum constant Constants.AnalysisType.<each case> reference cannot be qualified in a case label.
    for each of the cases that I try to use the enumerated type. My code
    looks something like this:
    switch (analysisType) {
    case Constants.AnalysisType.NONE:
        break;
    case Constants.AnalysisType.MVGAVG:
        break;
    }(With a number of cases omitted).
    where analysisType is the enumerated type defined in
    a file called Constants.java.
    The class where the error is occuring is located at:
    package myprog.ui.ViewPanelTab; and the enumerated type is declared at:
    package myprog.utility.Constants;I have the required import statements in the ViewPanelTab class.
    I have tried
    public, private, public static, private static as modifiers on the enumeration.
    Any ideas as to why eclipse won't let me do this.
    Thanks for any help
    Devon

    Why is it that the entire switch and all of its cases have the same locality ?By "locality" do you mean "scope" (i.e. the inability to declare two variables with the same name)? I find it rather irritating that I can't write switch (foo)
        case bar:
            int quux = ...
            break;
        case baz:
            int quux = ...
            break;
    }My guess as to the reason for the decision to disallow this is that otherwise removing a break statement could create a compiler error where there previously was none, and that this would be confusing. It is possible to create a fresh scope, though, by using braces:switch (foo)
        case bar:
            int quux = ...
            break;
        case baz:
            int quux = ...
            break;
    }

  • How to Use Switch Statement with Exclusion Group (radio buttons)?

    Wouldn't you know, just when I though I'd really be making progress, I've come across another problem I can't solve. In a homeowners insurance application I am building, there is an exclusion group that needs to set the value of several variables
    I have setup in the form properties/variables. These variables take on different values depending on the users choice.  For the exclusion group, in the object pallet, I have set the binding to normal, and have checked the "Specify Item Values" check box. Also the values for the choices have been assigned 1,2,3,4,5.
    Here is my code for the change event fir the exclusion group (This is exactly what I have tried). For now, the values for the variables to take on in the different cases, are completely arbitrary.
    switch (this.change.rawValue)              // I have tried so many things here
        case "1":                                        // I have tried the caption, single quotes in all combinations
            addLivingExp = "1";
            damageOthersProperty = "2";
            liabilityIncl = "3";
            maxCoverage = "4";
            minCoverage = "5";
            persProperty = "6";
            relatedPrivateStruct = "7";
            break;
        case "2":    
            addLivingExp = "10";
            damageOthersProperty = "20";
            liabilityIncl = "30";
            maxCoverage = "40";
            minCoverage = "50";
            persProperty = "60"
            relatedPrivateStruct = "70";
            break;
        case "3":    
            addLivingExp = "100";
            damageOthersProperty = "200";
            liabilityIncl = "300";
            maxCoverage = "400";
            minCoverage = "500";
            persProperty = "600"
            relatedPrivateStruct = "700";
            break;
        case "4":    
            addLivingExp = "1000";
            damageOthersProperty = "2000";
            liabilityIncl = "3000";
            maxCoverage = "4000";
            minCoverage = "5000";
            persProperty = "6000"
            relatedPrivateStruct = "7000";
            break;   
        case "5":    
            addLivingExp = "10000";
            damageOthersProperty = "20000";
            liabilityIncl = "30000";
            maxCoverage = "40000";
            minCoverage = "50000";
            persProperty = "60000"
            relatedPrivateStruct = "70000";
            break;   
        default:   
            minCoverage= 5;   
            break;
    There must be something obvious I am missing? Eternally grateful for advice on this.
    Stephen

    There are two issues in this script:
    1. You are not using the accessor 'value' to set form variables
    2. You are not correctly getting the value of the radio button list in the switch clause
    Please see the working script below.
    Ben Walsh
    www.avoka.com
    switch (this.rawValue) 
        case "1":                                       
            addLivingExp.value                  = "1";
            damageOthersProperty.value   = "2";
            liabilityIncl.value                      = "3";
            maxCoverage.value                 = "4";
            minCoverage.value                  = "5";
            persProperty.value                  = "6";
            relatedPrivateStruct.value        = "7";
            break;
        case "2":   
            addLivingExp.value                  = "10";
            damageOthersProperty.value   = "20";
            liabilityIncl.value                     = "30";
            maxCoverage.value                 = "40";
            minCoverage.value                  = "50";
            persProperty.value                  = "60"
            relatedPrivateStruct.value        = "70";
            break;
        case "3":   
            addLivingExp.value                 = "100";
            damageOthersProperty.value   = "200";
            liabilityIncl.value                     = "300";
            maxCoverage.value                 = "400";
            minCoverage.value                  = "500";
            persProperty.value                  = "600"
            relatedPrivateStruct.value        = "700";
            break;
        case "4":   
            addLivingExp.value                  = "1000";
            damageOthersProperty.value   = "2000";
            liabilityIncl.value                      = "3000";
            maxCoverage.value                 = "4000";
            minCoverage.value                  = "5000";
            persProperty.value                  = "6000"
            relatedPrivateStruct.value        = "7000";
            break; 
        case "5":   
            addLivingExp.value                  = "10000";
            damageOthersProperty.value   = "20000";
            liabilityIncl.value                      = "30000";
            maxCoverage.value                 = "40000";
            minCoverage.value                  = "50000";
            persProperty.value                  = "60000"
            relatedPrivateStruct.value        = "70000";
            break; 
        default:  
            minCoverage.value                 = 5;  
            break;

  • Default case not working in a switch statement

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

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

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

  • 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

  • Problem with switch statement

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

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

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

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

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

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

  • Help with Switch statements using Enums?

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

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

Maybe you are looking for

  • Email Template

    Hi, I have a new requirement that the standard text mail should be sent out as an HTML Email. I was thinking of a HTML template which would have "customized tags" which I can replace at run time based on the data from some datasource. The Email Templ

  • TextArea In CellRenderer doesn't initialize

    I'm new to AS3 so I'm not sure if this is something I'm doing wrong or a bug in the component... I have a List component and I'm using a movieclip as a custom cellRenderer - it's class extends MovieClip & implements ICellRenderer. In this movieclip I

  • How can i increase the number of screens on ipad

    I have some 5 screens on my ipad which makes a total of 100 Apps. Inwant to increase the number of screens or is there any limitation on number of Apps??? I had downloaded few apps from itunes store, but they are not visible now... Might be due to so

  • .Mac video chat with AIM

    Hi all. I'm trying out iChat with a friend of mine, but it isn't working. We're both on Mac's - I have a .Mac accound and my friend has an AIM account. We both get the video symbol in iChat, and once we click on it, we get a video window. So far so g

  • Print layout design - AR Invoice

    How to retrieve & display Business partner TNGST & CST Numbers in AR invoice Design,I have no reference to BP code in AR Invoice? (Table name - CRD7 - Fiscal ID of BP Master data)