Switch statment

hey
is there any way to create dynamic switch statment ?
if not what will be your solution of having something similar ?
thx
Mike

When people start asking questions about dynamic code flow it usually means that they need some refactoring and/or to use an appropriate collection.

Similar Messages

  • Switch Statments

    I am working on a program to print out a calendar given the month and year. I am trying to use a switch statement for the months. I want to know how I can access the information in the switch statement from a different method.
    What I don't know.
    1. If I need a parameter in the method of monthSwitch
    2. What the months part of switch(months) does.
    3. If I should have the month names and days listed here or in the other method I want to create to use this switch statement.
    I want to be able to find the days up through say the end of March. I am trying to find a way to then add up the days from January through to the end of March. (That is what the days += 31, etc. are for) I want to do this in another method. I just don't understand how to access the switch statement from another method. Thanks for helping!
    public void monthSwitch()
    String monthName;
    switch(months)
    case 1: monthName = "January";
    days+=31;
    break;
    case 2: monthName = "February";
    if(isLeapYear(d))
    days+=29;
    else
    days+=28;
    break;
    case 3: monthName = "March";
    days+=31;
    break;
    case 4: monthName = "April";
    days+=30;
    break;
    case 5: monthName = "May";
    days+=31;
    break;
    case 6: monthName = "June";
    days+=30;
    break;
    case 7: monthName = "July";
    days+=31;
    break;
    case 8: monthName = "August";
    days +=31;
    break;
    case 9: monthName = "September";
    days+=30;
    break;
    case 10: monthName = "October";
    days +=31;
    break;
    case 11: monthName = "November";
    days +=30;
    break;
    case 12: monthName = "December";
    days +=31;
    break;

    You might find the functionality of java.text.DateFormatSymbols and maybe java.util.GregorianCalendar helpful here. DateFormatSymbols provides an easy way to get the String names of the months and GregorianCalendar provides an easy way to get the maximum days in a specified month. Using these you may be able to get rid of the switch statement altogether. Either way the job gets done :)
    - Mr K

  • Switch Statement again

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    Yesterday, I received tremendous help, As a result, I am closer to understanding the switch statement and how it works.
    My program is designed to use 5 different input boxes. These represent a total for quizzes, homework assignments, 2 midterms, and a final exam.
    These are casted to double; then, they are added together and divided by five to obtain an average (the student's GPA). The GPA is then going to assigned a grade depending up the range in the If then statement.
    I intend on using a message box to inform the user of the GPA and another followed by another message box to show them their grade.
    I would like to incorporate the switch statement (so I can learn how to use it) to show them their grade.
    I know the code needs tweaking but this is what I have so far:
    import javax.swing.JOptionPane;
    public class Switchgrade{
    //declaration of class
    public static void main(String args[])
    //declaration of main
    String midone; String midtwo; String quiz; String homework; //declares variables to hold the grades, quiz and homework scores
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    char a; char b; char c; char d; char f;char grade;
    midone = JOptionPane.showInputDialog("Please enter the first midterm"); //first score to add
    one = Double.parseDouble(midone);
    midtwo = JOptionPane.showInputDialog("please enter second midterm"); //second midterm to add
    two = Double.parseDouble(midtwo);
    last = JOptionPane.showInputDialog("please enter final exam score");//final exam score to add
    three = Double.parseDouble(last);
    quiz = JOptionPane.showInputDialog("please enter quiz score");//quiz score to add
    four = Double.parseDouble(quiz);
    homework= JOptionPane.showInputDialog("please enter homework score");//homework score to add
    five = Double.parseDouble(homework);
    average = (one + two+ three + four + five)/5; //average of all five scores
    if(average >= 90)
    grade = 'a';
    else
    if(average >= 80 )
    grade = 'b';
    switch (grade)
    case a:
    JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");
    break;
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + b + ". \nYou failed.");
    break;
    System.exit(0);
    }//end of main
    }//end of class
    As you can see, I am only using two grades, just so I can learn to use it. However, when I go to compile this, I get this error message:
    constant expression required: case a:, with the ^ under the a.
    What does this error message me and how do I fix this.
    Thanks in advance for your help.

    case a:is trying to use a variable with the name "a" for the comparison. This is illegal in java
    what you want is
    case 'a':this will do a comparison against the char value 'a'

  • Switch Statement

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    I am trying to write an application that will calculate grades for a student. I can use the If Then Else Control structure for this (which runs) but I would like to incorporate the Switch Statement in place of the multiple if then else structure. Here is the code that I have for the application:
    import javax.swing.JOptionPane;
    public class Switchgrades
    public static void main(String args[])
    String midone; String midtwo; String quiz; String homework;
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    int a; int b; double c; double d; double f;int grade;
    midone = JOptionPane.showInputDialog("Please enter the first midterm"); //first score to add
    one = Double.parseDouble(midone);
    midtwo = JOptionPane.showInputDialog("please enter second midterm"); //second midterm to add
    two = Double.parseDouble(midtwo);
    last = JOptionPane.showInputDialog("please enter final exam score");//final exam score to add
    three = Double.parseDouble(last);
    quiz = JOptionPane.showInputDialog("please enter quiz score");//quiz score to add
    four = Double.parseDouble(quiz);
    homework= JOptionPane.showInputDialog("please enter homework score");//homework score to add
    five = Double.parseDouble(homework);
    average = (one + two+ three + four + five)/5; //average of all five scores
    switch (grade)
    case a: //this is where I become confused and lost. I don't what I need to do to make it run.
    {if(average >= 90)
         b = Integer.parseInt(average);
       JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");}
    / I am just using one choice to make it run. When I can make it run, I plan on incorporating the other grades.
    break;
    <=====================================================================>
    <=====================================================================>
    //else --->this is part of the if that works in another program
    // if(average >= 80 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a B");
    //else
    //if(average >= 70 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a C");
    //else
    //if(average >= 60 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a D");
    //else
    //if(average <= 60 )
    <=====================================================================>
    <=====================================================================>
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + average + ". \nYou failed.");
    System.exit(0);
    As you can see, I already have all the if then else statements set up--between the <==>. The program runs with the If's but I can two error messages when I incorporate the Switch statement.
    1) constant expression required.
    I have case a and i guess it is not a constant. Again, I don't understand switch well enough to figure what I need to do to correct it.
    2)"b = Integer.parseInt(average);" - cannot resolve the symbol--whatever that means. I have a "^" pointing at the period between Integer and parseInt.
    Can anyone help explain what I have to do to make this program work using Switch.
    I have not used Switch before and don't understand what I can use as opposed to what I must use for it to work.
    Thanks for your help.

    I don't really know how you want your program going, but here is what I think.
    1) From the start of the switch statement, where do you assign the value for "grade"? If you write the switch statement like below, you meant something like, if(grade == 'a'){...}, right!? Then, where did you get the "grade" from?
    switch (grade)
    case a:
    You may want declare variable "grade" as char and place if sentence like this before the switch.
    if(average >= 90)
    grade = 'a';
    else if(average >= 70)
    grade = 'b';
    switch (grade)
    case a:
    System.out.print("Your grade: A");
    break;
    case b:
    System.out.print("Your grade: A");
    break;
    Is that What you want???
    2)The method, Integer.parseInt(), takes String as parameter? Did you override this method? The variable "average" was declare as double, so why don't you just cast it to int??

  • If statment and semi colon questions

    This morning i was wondering why if(foo); {do stuff} doesn't through a compiler error. If it doesn't through a compiler error then that leads me to believe that it there is a reason to have a ; after an if statment. Any thoughts?
    I did notice that
    boolean foo = true;
    if (foo);
    print("hello")
    if(!foo);
    print("goodbye");
    }prints both hello and goodbye
    so I was wondering maybe it could act like a switch statment iwht out the breaks? i dunno. I was going to experiment with it but i got another task. That and I'm lazy and thought i'd ask before going on a wild goose chase
    No this has nothing to do with 45 minutes of wasted time I spent this morning wondering why my if statments weren't working.

    hmm i never even though about what would happen. Maybe i should go through all my code and double check...But then again, what do we pay the testers for.
    I guess they just leave that stuff in there to keep it interesting. I mean come on...who wants their code to work everytime? Think of the industry provided by those things. We have testers, maintence coders, people who rewrite the code, consolutants to look at code they wrote 10 years ago and are the only ones left around to find errors like that. Then the support staff, the helpdesk people. I wonder if those things aren't left in on purpose.
    i for one am going to put ; at the end of all my if's and only use one & or | from now on. Just doing my part to keep the economy strong.

  • Loop not working for check of duplicate values in a repeating table

    I have a form that is used for marking down problem items, describing the problems and assigning a value to the specified item. In some cases the problems belong to the same class. When they do, the value associated with the problem should only be marked once. If another problem in the same class is documented the value should not be recorded the second time. I have a variable that is called based on a switch statement in the exit event of the field that records the problem item number. The script in the variable is then supposed to check for duplicate values in the table. If no other problem item in that class is selected, then the problem value should be assigned a number. If another item from the same class has already been entered, then the problem value should just be left blank. I will paste the script for the variable below as well as the switch statement. When I used to call the variable based upon the change event for the problem item, the script work. At that time, the switch statement was related to a drop-down menu. We decided to get rid of the drop-down and just have the used type the item number. But to do so, I had to move the switch statement to the exit event for the field. when I did this, the script in the variable no longer worked properly. Here is the switch statment followed by the script in the variable:
    this.rawValue = this.rawValue.toLowerCase();
    var bEnableTextField = true;
    var i = "Inspection Criteria: ";
    var r = "Required Corrections: ";
    switch (this.rawValue)
      case "1a": // 1a- First debit option
        CorrectionsText.CorrectionLang = r+"Correction description for 1st debit";
        ViolCorrSection.ViolationsText.DebitVal = "C";
        ViolCorrSection.Reference.RefLanguage = i+"1st debit reference";
    break;
      case "1b": // 1b- Second debit option
        CorrectionsText.CorrectionLang = r+"Correction description for 2nd debit";
        ViolCorrSection.Reference.RefLanguage = i+"2nd debit reference";
        myScript.group1();
    break; //the script continues for various item numbers...
    ________________ variable script ________________________
    function group1()
    //Used in checking duplication of violations
    var oFields = xfa.resolveNodes("form1.MAINBODYSUB.ViolationsTableSubform.ViolationsTable.ViolCorrSectio n[*].ViolationsText.ItemNo"); // looks to resolve the repeating rows
    var nNodesLength = oFields.length; //assigns the number of rows to a variable
    var currentRow = xfa.resolveNode("form1.MAINBODYSUB.ViolationsTableSubform.ViolationsTable.ViolCorrSection ").index;
    var currentDebit = xfa.resolveNode("form1.MAINBODYSUB.ViolationsTableSubform.ViolationsTable.ViolCorrSection [" + currentRow + "].ViolationsText.DebitVal");
    for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) // this loops through Item Numbers looking for duplicate violations
    //console.println("nNodeCount: " + nNodeCount);
    var nFld = xfa.resolveNode("form1.MAINBODYSUB.ViolationsTableSubform.ViolationsTable.ViolCorrSection [" + nNodeCount + "]");
    //console.println("nFld.ViolationsText.ItemNo: " + nFld.ViolationsText.ItemNo.rawValue);
         if (nFld.ViolationsText.ItemNo.rawValue == "1a" || nFld.ViolationsText.ItemNo.rawValue == "1b" || nFld.ViolationsText.ItemNo.rawValue == "1c" || nFld.ViolationsText.ItemNo.rawValue == "1d") // looks for other 1s
              currentDebit.rawValue = "";
              nNodeCount = nNodesLength;  // stop loop
         else
            currentDebit.rawValue = "5";
    So, if you enter 1b the first time, you should get a value of 5 appearing in the debit value field. If you enter 1c next, because it belongs to the same group of class of problem items, there should be no value assigned. What happens now is that the values for 1b and 1c don't appear at all because the form thinks that the first 1b entry already existed.
    Any ideas? I have a stripped down version of the form that I can email to someone for reference if that would help. Thanks
    P.S. I am working with LiveCycle Designer ES 8.2.1....

    Hi,
    I can have a look at your form, but can you host it somewhere like Acrobat.com or google docs and add a link to it here.
    Regards
    Bruce

  • Positioning my objects

    how do you set the positioning of an object in java
    public class Panel extends JPanel{
    public void mymethod (int i){
    Graphics paper = this.getGraphics();
    paper.setColor(Color.black);
    Graphics hit = this.getGraphics();
    hit.setColor(Color.yellow);
    switch(i){
    case1:
    case2:
    public class Display extends JFrame{
    public static void main (String []args){
    Panel background = new Panel();
    Panel panel1 = new Panel(); ///////////////****************************
    Panel panel2 = new Panel(); ////////////////***********************************
    background.setPreferredSize(new Dimension(500, 200));
    MainWindow window = new MainWindow();
                    window.getContentPane().add(background);
    window.pack(); // Makes window display at proper size.
                    window.setVisible(true);
    }// main
    }I WANT TO ADD mypanel1 and mypanel2 to the background of Display which i have defined. But when i add it i want it to access the switch statment i.e panel1.mymethod(1); and panel2.mymehtod(2); and add this then put panel2 to the right 100 pixel of panel1
    I want to make instances of MyClass
    MyClass myclass1=new MyClass();
    MyClass myclass2=new MyClass();i then want to access the switch statment
    myclass1.mymehtod(1);
    myclass2.mymehtod(2);and i want to display these instances on a JPanel in another class which myclass1 should be on the left and myclass2 on the right 100 pixels away from the other.
    Please show any code

    surprise wrote:
    how do you set the positioning of an object in javaBefore you worry about this, you had better go through the Sun Swing tutorials. You are making a critical error trying to mix AWT components (i.e., Panels) with Swing components. Unless you really know what you are doing (and in this situation, you don't), this shouldn't be done.
    and i want to display these instances on a JPanel in another class which myclass1 should be on the left and myclass2 on the right 100 pixels away from the other.You should read up on the Layout managers. BoxLayout may work well here, though again, first go through the basic Swing tutorials.
    Please show any code???
    aw h�ll, you've already been told much of this in your cross-post. You've also got another cross-post in the Java-2D forum. Unless you are trying to piss us off, you'd best refrain from cross-posting.
    Edited by: Encephalopathic on Feb 18, 2008 9:53 AM

  • Runtime Casting

    I have a hashtable with different objects types inside it. Since they are swing objects, all of them are handled by a single function.
    Enumeration enum = hash.keys();
    while( enum.hasMoreElements() )
         // The key is always a String, so a hard cast is acceptable
         String key = (String)enum.nextElement();
         Object val = hash.get(key);
         // Try Use Reflection to retrieve the class
         Class interfaceClass = Class.forName(val);    // ??
         panel.add( (interfaceClass)val  );            // ??
    }What I would like to do is cast these objects without having to write a switch statment to delimit hard casts. The following code works, but since I have to hard code the answers is *obviously a poor way to do it.
    Enumeration enum = hash.keys();
    while( enum.hasMoreElements() )
         String key = (String)enum.nextElement();
         Object val = hash.get(key);
         // Use Reflection to retrieve the class
         Class interfaceClass = val.getClass();
         String className = interfaceClass.getName();
         if( className.endsWith("JButton") )
              panel.add( (JButton)val  );
         else if( className.endsWith("JCheckBox") )
              panel.add( (JCheckBox)val  );
    }Any help with the dynamic casting problem would be appericated.
    ~Kullgen
    (PS, After searching the forums for a solution, I find that when people ask this question they are invariably flamed for poor design. This is not a design question, but just a problem with having to use the clunky java swing. IMHO Swing was very poorly designed, and thus leaves itself open to the problems above. I want this to be a post about runtime casting, not about design)

    Since all the has elements are Swing componets they are all instances
    of java.awt.Component. So simply cast to that and everything will be
    just fine and dandy. No need for lots of switch statements.
    For example:
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    public class Kullgen1
         public static void main(String[] argv)
              Hashtable hash= new Hashtable();
              hash.put("Button", new JButton("Button"));
              hash.put("Label", new JLabel("Label"));
              hash.put("TextField", new JTextField("TextField"));
              JFrame frame= new JFrame();
              JPanel panel= new JPanel(new GridLayout(0,1));
              frame.getContentPane().add(panel);
              Iterator components= hash.values().iterator();
              while(components.hasNext())
                   panel.add((Component) components.next());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }

  • Finding which menu item has been clicked

    Does oracle forms have anyway of knowing which menu item has been clicked.
    I have a security structure set up where menu items are made visible depending on their name, which in turn is based on the individual forms that a particular user can access.
    I would like to write a generic method for all menu items where it uses the name of the clicked menu item to perform a query, the result could be used to open a new form.
    So is there a build in or some 'secret source' which tells me the name or gives me the id of a clicked menu item?
    Message was edited by:
    gazbarber

    Not entirely sure what you mean, are you sugesting i have a generic method with a switch statment and uses the input paramter to decide what to do?
    It's not really what i'm after, rather I already have the name of the menu item in the database, the same table also contains the module filename that clicking the button should go to.
    So the idea would be somthing like
    declare
    begin
    select module name into new form from secutity table where menu item = :system.current menu item;
    open_form(new form);
    end;
    :sysem.current menu item is the missing ingreadiant.
    My menu has many items in the hundreds i think so even the generic switch staement would be pretty tedious and i want changes in the database to be felt system wide as they are else where in my system.
    Thanks for you help and i hope this explains my question better.
    Regards,
    Gareth
    Message was edited by:
    gazbarber

  • Int to string to string array

    Sorry, if my question is too wordy.
    First, the problem -- I am reading integers into my application and converting the those into strings using valueOf(). I then need to use those strings in a switch statment. The only way I could figure how to do this was to use the same String variable in each switch statement but change the the message to fit each case. My professor suggested I use an array list instead.
    Second, the question -- how can I convert the String I have generated into a String Array and use the indexing of the array to correspond to the specific text for each case?
    Thank you.

    indeed, you can't use the switch mechanism on strings.
    but, if the requirement is that you convert an integer into a string and then switch on those (I don't know why...) from an array of the values, swap the String value back into an int and switch from there.

  • Java.sql.Types.RAW

    I know you can map a LONG RAW sql type to the java class oracle.sql.RAW when wrapping the java code in your pl/sql wrapper. The problem I am having is that within my java code I am returning result set and using reslutSetMetaData to determine if the column is a varchar or clob with a switch statment and a case comparison using java.sql.Types.whatever sql type i am looking for. I am running into a problem when trying to write a case statement for long raw columns. What would be the statement to use for this. Below is an example of the code.
    int type = rsmd.getColumnType(1);
    switch (type) {
    case java.sql.Types.CLOB:
    code to execute when CLOB type
    break;
    case java.sql.Types.Raw:
    code to execute when LONG RAW type
    break;
    Thanks in advance,
    Kevin
    null

    user1330140 wrote:
    ...the return type which is defined inside DBMS_XDB_VERSION package
    I think there are some threads somewhere that points to Oracle documentation somewhere that says that is not possible with JDBC.
    I could certainly be mistaken however.
    If I am not mistaken then you would need to
    1. Wrap the call to that in another proc.
    2. That proc extracts the result into something that is visible in the jdbc driver.

  • CharAT Throws StringIndexOutOfBoundsException.

    The program works fine until the user has finished entering the Swell Heights then it returns to the menu and then Throws this silly exception.
    =(
    import java.util.Scanner; //import the Scanner Class
    import java.lang.reflect.Array; //import the Array Class
    @Program Name: SwellHeights.java
    @Purpose: To get swell information and the display
               proccessed information about the swells.
    //Start of the Program
    public class SwellHeights
      //creates a Global Array so that the functions can get access to it
      public static float[] arraySwellHeight = new float[7];
      //Start of the MAIN function
      public static void main(String args[])
        float day = 0; //Init var to get data from dayLargeSwell()
        float smallest = 0; //Init var to get data from smallSwell()
        float largest = 0; //Init var to get data from largeSwell()
        float average = 0; //Init var to get data from averageSwell()
        Scanner in = new Scanner (System.in); //Creates a scanner to capture input   
        char choice; //declare var for use in Case Statement
        do //Starts do while loop
           //Program heading
           System.out.println("SWELL HEIGHT ANALYSIS PROGRAM");
           System.out.println("*****************************");
           System.out.println("");
           System.out.println("a)    Enter maximum daily swell heights");
           System.out.println("b)    Analyse swell height figures");
           System.out.println("c)    Exit program");
           System.out.println("");
           System.out.println("Enter Option a, b or c");
           System.out.println("Please use lowercase for your answer.");
           System.out.println("");
           String s = in.nextLine(); //Sets user input as s
           choice = s.charAt(0); //charAt only reads the 1st char in s
           //Switch statment to define where the program will go to
           switch(choice)
               //If a in input form user it runs this section
               case 'a' :
                     int count; //declares a counter to use in for loop
                     System.out.println("");
                     System.out.println("ENTER MAXIMUM SWELL HEIGHTS FOR THE LAST 7 DAYS");
                     System.out.println("===============================================");
                     System.out.println("Note: Input swell height figures in metres");
                     System.out.println("");
                     System.out.println("Enter 7 daily Swell Hieghts\n");
                     for (count = 0; count < 7; count++)
                     //This loop will run 7 times
                          System.out.print(" Enter swell heights for day " + (count+1)+" $: ");
                          SwellHeights.arraySwellHeight [count] = in.nextFloat();
                          System.out.println(SwellHeights.arraySwellHeight [count]);
                          //This is creating an Array with 7 elements
                    System.out.println("");
                    //Stops the program from carrying on to case b
                    break;
               //If b is input from user it runs this section
               case 'b' :
                    System.out.println("");
                    System.out.println("MAXIMUN DAILY SWELL HEIGHTS FOR THE WEEK"); 
                    System.out.println("****************************************");
                    System.out.println("");
                    System.out.println("   Day  Metres");
                    System.out.println("   ---  ------");
                    // + SwellHeights.arraySwellHeight[#] displays what is inside that element
                    System.out.println("     1  " + SwellHeights.arraySwellHeight[0]);
                    System.out.println("     2  " + SwellHeights.arraySwellHeight[1]);
                    System.out.println("     3  " + SwellHeights.arraySwellHeight[2]);
                    System.out.println("     4  " + SwellHeights.arraySwellHeight[3]);
                    System.out.println("     5  " + SwellHeights.arraySwellHeight[4]);
                    System.out.println("     6  " + SwellHeights.arraySwellHeight[5]);
                    System.out.println("     7  " + SwellHeights.arraySwellHeight[6]);
                    System.out.println("");
                    System.out.println("============================================================================");
                    System.out.print("Average swell height    : " );
                    average = averageSwell(); //calls the averageSwell() function
                    System.out.println(average); //prints out the result of that functions process
                    System.out.print("Smallest swell height   : " );
                    smallest = smallSwell(); //calles the  smallSwell() function
                    System.out.println(smallest); //prints out the result of that funtions process
                    System.out.print("Largest swell height    : " );
                    largest = largeSwell(); //calles the largeSwell() function
                    System.out.print(largest); //prints out the result of the functions process
                    System.out.print(" metres occured on day ");
                    day = dayLargeSwell(); //calles the daylargeSwell() function
                    System.out.println(day); //prints out the result of that functions process
                    System.out.println("============================================================================");
                    System.out.println("");
                    //Stops the program from carrying on to case c
                    break;
               //If c in input form user it runs this section  
               case 'c' :
                    System.out.println("");
                    System.out.println("Thank you and Goodbye");
                    //Stops the program from carrying on to default
                    break;
               default :
                    System.out.println(choice+ " Is An Invalid Selection" );
                    System.out.println("");
                    //Stops the program from exiting the case statement
                    break;
              //End of Case Statement
        //End of Do-While Loop, when user enters c
        while(choice != 'c');
      //End of main()
      Purpose: To calculate the average swell
               height from the values in the
               Array.
      @return: Returns the average to be
               displayed in main()   
      public static float averageSwell()
        int count = 0; //Init var for Do-While Loop
        float total = 0.0f; //Init var for the total
        float average = 0.0f; //Init var to hold the average
        //Start of Do-While loop
        do
          //Accumulate Total
           total = total + SwellHeights.arraySwellHeight[count];
           count = count + 1;
        //Finishes when count is equal to 7
        while (count < 7);
        //Average is total / number of elements
        average = total/count;
        //Returns the average var to main()
        return average;
       }//end of averageSwell()
      Purpose: To calculate the minimum swell
               height from the values in the
               Array.
      @return: Returns the minimum to be
               displayed in main()   
      public static float smallSwell()
        int count = 0; //Init var for Do-While Loop
        float minimum; // Declare float to hold minimum
        //minimum is then assigned the first element
        minimum = SwellHeights.arraySwellHeight[0];
        //Start of Do-While loop
        do
          //Check for new minimum
           if (SwellHeights.arraySwellHeight[count] < minimum)
             //New minimum
             minimum = SwellHeights.arraySwellHeight[count];
          //Incrementing count
          count = count + 1;
        //Finishes when count is equal to 7
        while (count < 7);
        //Returns the minimum var to main()
        return minimum;
       } //End of smallSwell()
      Purpose: To calculate the maximum swell
               height from the values in the
               Array.
      @return: Returns the maximum to be
               displayed in main()   
      public static float largeSwell()
        int count = 0; //Init var for Do-While Loop
        float maximum; // Declare float to hold maximum
        //maximum is then assigned the first element
        maximum = SwellHeights.arraySwellHeight[0];
        //Start of Do-While loop
        do
          //Check for new maximum
           if (SwellHeights.arraySwellHeight[count] > maximum)
            //New maximum
            maximum = SwellHeights.arraySwellHeight[count];
           //Incrementing count
           count = count + 1;
        //Finishes when count is equal to 7
        while (count < 7);
        //Returns the maximum var to main()
        return maximum;  
       } //End of largeSwell()
      Purpose: To calculate the day of the
               largest swell height from the
               values in the Array.
      @return: Returns the day of the largest
               swell to be displayed in main()   
      public static float dayLargeSwell()
        int count = 0; //Init var for Do-While Loop
        int day = 0; //Init var to hold days
        float maximum; //Declare float to hold maximum
        //maximum is then assigned the first element
        maximum = SwellHeights.arraySwellHeight[0];
        //Start of Do-While loop
        do
           //Check for new maximum
           if (SwellHeights.arraySwellHeight[count] > maximum)
            //New maximum
            maximum = SwellHeights.arraySwellHeight[count];
            //Maximum element number caputured
            day = count + 1;
           //Incrementing count
           count = count + 1;
        //Finishes when count is equal to 7
        while (count < 7);
        //Returns the day var to main()
        return day;  
      } //End of dayLargeSwell
    } //End of Program

    charAt throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string.
    A quick look at your code shows that you are using charAt only once:String s = in.nextLine(); //Sets user input as s
    choice = s.charAt(0); //charAt only reads the 1st char in sThe conclusion is that s has a length of zero.
    I guess this could happen when user hits the return key without entering a character (or might come from Scanner behaviour when using nextFloat() followed by nextLine(), I don't know much about Scanner as I'm still stuck to 1.4 .)
    You could therefore add a check on user input before trying to extract the character, something like:String s = null;
    while((s = in.nextLine()).length() < 1); //read user input until it is not empty
    choice = s.charAt(0); //charAt only reads the 1st char in sHope it helps.

  • Saving/restoring treeSet

    I've got a customer database using TreeSet API. I'm trying to make a method for saving and restoring the treeset, but I'm a little confused. Any help would be appreciated:
    Thanks
    public class TreeSetProject {
       public static void main(String[] args) throws Exception {
         //main method
              int menuCode, add, delete;
              char check;
              boolean search = false, repeat = false, done = false, exist = false;
              TreeSet customer = new TreeSet();
             while (!done) {
              //loops until boolean done becomes true
                  menuCode = Integer.parseInt(JOptionPane.showInputDialog(null,
                       "1. Add customer"
                            + "\n2. Delete customer"
                                 + "\n3. Search for a customer"
                                      + "\n4. List all customers"
                                           + "\n5. Save your progress"
                                                + "\n6. Restore from last save point"
                                                      + "\n7.Delete all entries"
                                                          + "\n **Enter 0 to end program**"
                                                               + "\n Please enter a choice: "));
                   //Creates choices in menu
                   switch (menuCode) {
                   //creates switch statment for menu
                        case 1:
                             String customerToAdd = JOptionPane.showInputDialog(null,
                                  "Customer's name: ");
                             repeat = customer.contains(customerToAdd);
                             if (repeat == false)
                                  customer.add(customerToAdd);
                                  JOptionPane.showMessageDialog(null, customerToAdd + " was successfully added to the list");
                             else
                                  JOptionPane.showMessageDialog(null, "Sorry, but " + customerToAdd + " is already in the list");
                             break;
                             //Allows user to add customers and checks for duplicates
                        case 2:
                             String customerToDelete = JOptionPane.showInputDialog(null,
                                  "Customer to delete: ");
                             exist = customer.contains(customerToDelete);
                             if (exist == true)
                                  customer.remove(customerToDelete);
                                  JOptionPane.showMessageDialog(null, customerToDelete + " was successfully removed from the list");
                             else
                                  JOptionPane.showMessageDialog(null, "Sorry, but " + customerToDelete + " does not exist");
                             break;
                             //Allows user to delete customers and checks to make sure the record exists
                        case 3:
                        String customerToSearch = JOptionPane.showInputDialog(null,
                                  "Customer to search for: ");
                             search = customer.contains(customerToSearch);
                             if (search == true)
                                  JOptionPane.showMessageDialog(null, customerToSearch + " is in the database");
                             else
                                  JOptionPane.showMessageDialog(null, "Sorry, but " + customerToSearch + " is not in the database");
                             break;
                             //Allows user to search for a customer
                        case 4:
                             JOptionPane.showMessageDialog(null, customer.toArray());
                             break;
                             //prints a list of all data
                        case 7:
                             customer.removeAll(customer);
                        break;
                        //removes all entries if case 7 is chosen     
                        default:
                             JOptionPane.showMessageDialog(null, "Bad input. Read the choices carefully!");
                             //Tells user to retry their selection if they don't enter a choice from 0-7
                   }//ends switch statment     
              }//ends while loop
         }//ends main method
    }//ends class

    dazeman wrote:
    I've got a customer database using TreeSet API. I'm trying to make a method for saving and restoring the treeset, but I'm a little confused. Any help would be appreciated:
    Thanks
    ...Ok, but what is your question?
    By looking at the title of your thread "Saving/restoring treeSet" I'd say: have a look at Serialization:
    http://www.deitel.com/articles/java_tutorials/20050923/IntroductionToObjectSerialization.html
    But if you have a specific question about the code you posted, feel free to ask it here.

  • JRadioButton's and Button Groups

    I have a button group with some radio buttons, but i don't want any actions to be done untill a JButton is pressed. In my actionPreformed for the JButton is there a way to make a switch statment where the different cases are the different radio button's that might be pressed. i'm not sure if i'm saying it clearly so here is an outline of what i wasnt to do.
    switch ( myButtonGroup.radioButtonSelected() )
    case radioButton1:
    blah blah blah
    case radioButton2:
    blah blah
    and so on.
    thanks for any help.

    HI,
    If I understand your question correctly,
    what you can do is if/else
    if(buttonGroup.isSelected(radioButton1.getModel()))
    else if(buttonGroup.isSelected(radioButton2.getModel()))
    Hope this helps

  • Get graphics

    I have a class called Myclass and it has a switch statment
    and in the gui class which extends JFrame i want to make instances of the myclass class. which ive done
    BASICALLY I HAVE A CLASS CALLED myclass AND I WANT TO PUT INSTANCES OF IT IN THE create class, AND PASS PARAMETER TO IT TO DECIDE WHAT TO DRAW. EG. myclass myclass1 = new myclass();
    then say myclass1.myswitch(8) and draw this on the screen in the clas gui.
    if possible pease show code I wuld would to position one instance of the left of the screen, and then the other instance 100 pixelx to the right of it and so on.
    i want to pass it a parameter of 8 which will then go through to the swicth statmment as decide what to display. Now how do i display this on the screen in gui class
    window.add(myclass1.myswitch(8));
    This line is wrong
    class Myclass extends JPanel{
    public Myclass(){
    super();
    public void myswitch(int i){
    Graphics paper = this.getGraphics();
    paper.setColor(Color.black);
    Graphics remove = this.getGraphics();
    hit.setColor(Color.white);
    switch (i){
    case 1:
    paper.drawLine(20,20,50,50);
    hit.drawLine(70,70,50,50)
    // code to draw football colour black
    case 5:
    // code to draw rugby ball colour black
    default:
    // draw trainers colour black
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class create extends JFrame{
    public static void main(String []args){
    Myclass myclass1 = new Myclass();
    myclass1.setPreferredSize(new Dimension(100, 100));
    myclass1.setBackground(Color.black);
    create mycreate = new create();
    mycreate.add( myclass1 );
    mycreate.setVisible(true);
    myclass1.mymethod(8); // trying to put this on the screen but doesnt work
    }

    sorry for the inconvienece i cause i shouldnt have reposted i though maybe in another section i would get more replies.
    Sorry i should have been more explicit your code works perferctly boo bear.
    But now i have the troble
    import java.awt.*;
    import javax.swing.*;
    public class MainWindow extends JFrame {
         public static void main(String[] args) {
              // SwingUtilities.invokeLater ensures your GUI is created on the
              // Event Dispatch Thread.
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        MyPanel panel = new MyPanel();
                        panel.setPreferredSize(new Dimension(100, 100));
                        //panel.setBackground(Color.black);
                        MainWindow window = new MainWindow();
                        window.getContentPane().add(panel);
                        window.setDefaultCloseOperation(EXIT_ON_CLOSE);
                        window.pack(); // Makes window display at proper size.
                        window.setVisible(true);
                        panel.setPaintState(1);
         static class MyPanel extends JPanel {
              private int paintState;
              public MyPanel() {
                   super();
              public void setPaintState(int state) {
                   this.paintState = state;
                   repaint(); // Tells the panel to repaint itself since state has changed
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.setColor(Color.black);
                   switch (paintState) {
                        case 1:
                             // code to draw football colour black
                             break;
                        case 5:
                             // code to draw rugby ball colour black
                             break;
                        default:
                             // draw trainers colour black
                             break;
    }I want to set two colours one red and one yellow
    paintComponent(Graphics g, Graphics hit)
    super.paintComponent(g);
                   g.setColor(Color.red);
    super.paintComponent(hit);
    hit.setColor(Color.yellow);then when i code through the switch statment i.e
    switch (paintState){
    case1:
    g.drawLine(20,20,80,80);
    hit.drawLine(10,10,40,40);
    }but when i compile nothing (no lines) comes up and once i remove hit.drawLine(10,10,40,40); super.paintComponent(hit); and hit.setColor(Color.yellow);it display the orgininal line.
    i seems i am unable to set two different colours

Maybe you are looking for

  • HT3775 how can i convert a mod file (on vlc) to mp4 to work on quicktime

    how can i convert a mod file (on vlc) to mp4 to work on quicktime when i connected my video camera and imported the videos, they're default is to play on vlc they are mod files i want to edit the videos on imovie and for that the videos need to be mp

  • Disc Drive won't take DVD+RW

    I want to free up some of the space on my macbook, so I'm trying to put some of my photos on a DVD+RW. The Brand is Memorex. At the top it says "rewritable-4X-4.7GB-120min". When I put the disc in the drive, it makes all the usual noises, and sounds

  • X230 downgrade to 7 issues

    Hi, We bought 3 brand new X230 with Windows8 Preinstalled, we needed to downgrade the system to windows 7. The problem is that these Notebooks comes with no DVD reader even in the Docking Station......I installed Windows 7 cause we needed to built  t

  • Smartform - Output window (Accept, Cancel, Print, Preview)

    Dears experts, when i execute a preview of a Purchase Order, a message windows appears and you can select the diferents message( print, external send) and  Accept, Cancel, Print or Preview. I want to do 2 things. - I only want to view Accept and Canc

  • How to export full bleed pdf

    New to cs5 & need to produce a full bleed pdf to make a business card..Is it better to do in Lightroom?