A function containing switch statement and foreach-object loop

Hello Guys
in my testdomain.lab, i have following five OUs in mt test AD structure:
'OUusers', 'OUcomputers','OUservers','OUadministrators','OUhelpdesks'.
i have created following five variables:
$OUusers = 'ou=OUusers,dc=mytestdomain,dc=lab'
$OUcomputers = 'ou=OUcomputers,dc=mytestdomain,dc=lab'and so on
now i have created a function which gets this names as input &
foreach-object creates the related OU.
but the problem is sometimes when i run my function, maybe some of those five OUs
currently exist in AD so this will cause a
terminating error. 
so i know i must use switch statement to define conditions like this:
if $OUusers doesn't exist, execute this :  new-ADOrganizationalunit $OUusers
if $OUcomputers doesn't exist, execute this :  new-ADOrganizationalunit $OUcomputers
and so on...
it's a long time which i am trying to create a
function which contains such switch statement & properly forEach-object loop.
i have studied switch and foreach-object loops , but this scenario is complicated for me & i was unable to get the correct code.
Function createOUs {
# combination of ForEach-Object and Switch statement here
may someone give me the correct
command please?
thanks a lot

Like this:
$CompanyRoot=tha'ou=MyCompany, dc=mytestdomain,dc=lab'
New-ADOrganizationalUnit -Name MyCompany -ErrorAction SilentlyContinue
$ous='Users', 'Computers','Servers','Administrators','Helpdesk'
foreach($ou in $ous){
New-ADOrganizationalUnit -Name $ou -Path $companyroot -ErrorAction SilentlyContinue
¯\_(ツ)_/¯
jrv, That can't be the solution because when you running a command which tries to creates an OU
which already exist in AD, causes a
terminating error which has two caveats:
1- shows red error message on screen
2- stops and doesn't continue to execute next lines of code
Note that -ea silentlycontinue and -ea ignore have no effect on
terminating errors and they cn't hide error messages, also script can't continue.
i examined that.
to get sure, run this function in your test AD & see the result:
function createOUs {
New-ADOrganizationalUnit -Name 'an-existing-ou' -Protected 0 -ea SilentlyContinue # you see that -ea silentlycontinue has no effect here
New-ADOrganizationalUnit -Name '2ndOU' -Protected 0 -ea SilentlyContinue # you see that because the previous error has been a terminating error, command execution has been stopped and this 2nd OU hasn't been creatde
 another bad news is ( as i tested), if we query for an Organizational Unit which doesn't exist in AD , it generates a terminating error as well, so again here -ea has no effect.
test this:
PS C:\> Get-ADOrganizationalUnit -identity 'ou=nonesense,dc=yourDomain,dc=lab' -ea ignore
error doesn't disapear ;-)

Similar Messages

  • There are no functions containing returntype = 'query' and access!

    Hi there
    I am trying to add a recordset after defining a datasource and I keep getting the error when I do a CFC query search
    there are no functions containing returntype = 'query' and access!. I have attached an image to show the error messag I get.
    Can someone help me fix this? my datasource shows up as correctly configured in cold fusion and the mysql database is well configured as well.

    okay, adding another function to the CFC and saving it makes
    it suddenly, magically visible to the function invocation window?
    I don't understand.

  • Weird error when calling AS function to switch state from embedded HTML page

    Hey everyone,
    I'm developing an application that has 5 states in it. The
    welcome state is set by default. I wrote a function called
    changeState that looks like this:
    internal function changeState(sState:String):void
    currentState = sState;
    Now, inside the registration state, there is an mx:HTML
    component named htmlReg with the following attribute:
    htmlDOMInitialize="htmlReg.htmlLoader.window.changeState =
    changeState;"
    Inside the plain handcoded HTML web page that's loaded,
    there's a button that looks like this:
    <button onClick="changeState('Welcome')">Back to
    Welcome</button>
    The idea being, when the user clicks the HTML button, it
    calls the AS function changeState('Welcome') and the user gets
    taken back to the welcome screen.
    The good news is that when I click this button, it works
    fine, and I'm taken back to the welcome state.
    The bad news is that when I then switch to another state
    (using an mx:Button in the welcome state), I get the following
    error:
    TypeError: Error #1009: Cannot access a property or method of
    a null object reference.
    at flash.html::HTMLLoader/onFocusOut()
    I'm having trouble figuring out why this is happening, and
    what to do about it.
    Two additional data points:
    1) If I add an mx:Button to the registration state with a
    click="changeState('Welcome')" handler, it works as expected and I
    don't get an error. I only get this error when clicking the HTML
    button, which calls the same function in the same way.
    2) If I move the mx:HTML component out of the registration
    state and into the main application, I don't get this error any
    more (and the HTML state change button still works as expected).
    Anybody have any clues or ideas as to what might be
    happening? Or ideas as to what I might try to collect more data
    points? Or even workarounds to accomplish the same task in a
    different way?
    Thanks in advance.

    Probably what is happening is that when you change states,
    the HTML control is removed from the stage. However, the HTMLLoader
    (which is wrapped by mx:HTML) does seem to know that it has been
    removed, and losing focus, it's internal handler for the focusOut
    event access some property that requires it to be on the stage --
    hence the null object reference.
    You should report this bug at
    http://www.adobe.com/go/wish
    and provide a sample that demonstrates the issue.
    A workaround might be to change the focus to another object
    with stage.assignFocus() before you change states.

  • Switch statement and case variables

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

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

  • Return statement and accessing object's variable

    I want to return object variable but I am not sure how
    that is the constructor which takes int as arg.
    public class VHS implements MyInterface
    int year;
    public VHS (int year)
    this.year = year;
    Now I create new object in main class
    VHS currentMovie;
    currentMovie = new VHS(1995);
    int movieYear;
    System.out.println("enter the year of movie: ");
    movieYear=Keyboard.readInt();
    currentMovie.movieTitle(movieYear);
    System.out.println("passed as parameter when creating obj = new VHS(" currentMovie ")" );
    currentMovie.userInput();
    // it printout the year entered by user and works fine, however the thing above it dont, it is supposed to return the same thing
    // the problem is with currentMovie. I know I could do it differently, but I am curious if I could somehow printout the argument that was passed to the object using currentMovie.
    I quess I would need toString method but if I create it I got a message incompatible types :
    public String toString()
    return year; // year is an int
    If anyone is able to understand what I am trying to do, please respond
    and thank you , this forum already helped me very much, much more than my professors :) who are extremally weird

    public String toString()
    return year; // year is an int
    }Of course it says incompatible types. You're trying to return with an int, when you declared that the method should return String.
    String, although it is an object in Java, is treated differently. You can convert any primitive value to String easily. You also can convert any kind of objects to String as well.
    In case of primitives, one of the "wrapper" classes will be used to convert the primitive to string. In case of objects, the toString method of the object will be used to convert.
    Since you want to convert an int (primitive) to string, the easiest way perhaps:
    return "" + year;
    Since one of the operands has the type of String, the operator will change to be the "concatenate strings" operator, and the other operand will be converted to string. The returning type of the expression is String, and that's what it should be.
    You also might use the static method of the Integer wrapper class:
    return Integer.toString(year).

  • Saving object graph containing transient-new and attached objects

    Problem
    We have simple FK relationship A->B relationship and create inside the transaction (service façade method) a new instance of A:
    A a = new A().
    Later in the same transaction we read independent instance of B from DB and put it in the ralationship with A:
    a.setB(b);
    Afterthat (in the same transaction) we want to save the object graphstarting with instance ‘a’. We do it with
    pm.attachCopy(a);
    We get an Exception:
    <4|false|4.0.0EA5> kodo.util.UserException:
    The instance "mypackage.A-pypackage.A-14638" is already managed.
    FailedObject: mypackage.A - mypackage.A -14638 at kodo.jdo.PersistenceManagerImpl.processArgument(PersistenceManagerImpl.java:1259)
    Known solution
    Detach the instance ‘b’ before calling pm.attachCopy(a);
    We could achieve this for example using Autodetach=commit and puting read and save operations in separate transactional methods (façade calls).
    This solution is unsatifying, because we want to be able to manipulate object graph inside the transaction without caring explicitly about attach/detach semantic.
    Question
    We habe an heterogeneous object graph consisting of attached, detached and transient-new objects. How can we make the graph persistent with one API call on the roor object ?
    Which mapping settings have to be done ? How KODO decides which object is ‘new’ and shhould be inserted and which obejct has to be updated ?

    Denis,
    Even the makePersistent (...) call is redundant but not harmful as long
    as the instance is managed (and not detached).
    Denis Sukhoroslov wrote:
    Hi Andre,
    Not clear, why do you call pm.attachCopy(a) at all. I haven't worked with
    kodo 4.0 yet, but in 3.4.0 you just need to call pm.makePersistent(a). In
    the same way you can persist whole object graph, AFAIK.
    Denis.
    "Andre Teshler" <[email protected]> wrote in message
    news:[email protected]..
    Problem
    We have simple FK relationship A->B relationship and create inside the
    transaction (service fa??ade method) a new instance of A:
    A a = new A().
    Later in the same transaction we read independent instance of B from DB
    and put it in the ralationship with A:
    a.setB(b);
    Afterthat (in the same transaction) we want to save the object
    graphstarting with instance ???a???. We do it with
    pm.attachCopy(a);
    We get an Exception:
    <4|false|4.0.0EA5> kodo.util.UserException:
    The instance "mypackage.A-pypackage.A-14638" is already managed.
    FailedObject: mypackage.A - mypackage.A -14638 at
    kodo.jdo.PersistenceManagerImpl.processArgument(PersistenceManagerImpl.java:1259)
    Known solution
    Detach the instance ???b??? before calling pm.attachCopy(a);
    We could achieve this for example using Autodetach=commit and puting read
    and save operations in separate transactional methods (fa??ade calls).
    This solution is unsatifying, because we want to be able to manipulate
    object graph inside the transaction without caring explicitly about
    attach/detach semantic.
    Question
    We habe an heterogeneous object graph consisting of attached, detached and
    transient-new objects. How can we make the graph persistent with one API
    call on the roor object ?
    Which mapping settings have to be done ? How KODO decides which object is
    ???new??? and shhould be inserted and which obejct has to be updated ?

  • Static Methods & Switch Statement

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

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

  • Problems with switch statement

    He everyone,
    i tried to built a page with 4 buttons. Each button is a symbol that contains 2 png´2 which are the the button Designs. If you click on  button 1 it should move on the screen. If you click it again it should moves back. and if you click on another button while button1 is active then button1 should move back to starting position and button 2 should move on screen.
    i use a switch statement and a variable.
    on composition ready i used
    sym.setVariable("current","");
    to set the Variable
    on each button(one of the png inside the symbols) i used:
    var current = sym.getComposition.getStage.getVariable("current");
    switch (current)
    case "" :
    sym.play("in");
    break;
    case button1 :
    sym.play("out");
    break;
    default :
    sym.getComposition.getStage.getSymbol(current).play("out");
    sym.play("in");
    break;
    ad each animation of the buttons are labels for the in and out animation. There are also triggers that change the variable current on the stage
    sym.getComposition.getStage.setVariable("current","button1");
    if i test it inside of a browser and click on one of the button nothing happens.
    i´m not sure what´s my mistake.
    can anyone help me?
    regards
    mr.monsen

    Hi,
    Some syntax errors in red:
    var current = sym.getComposition().getStage().getVariable("current");
    switch (current)
    case "" :
    sym.play("in");
    break;
    case "button1" :
    sym.play("out");
    break;
    default :
    sym.getComposition().getStage().getSymbol(current).play("out");
    sym.play("in");
    sym.getComposition().getStage().setVariable("current","button1");

  • How to optimize a MDX aggregation functions containing "Exists"?

    I have the following calculated measure:
    sum(([D Player].[Player Name].[All],
    exists([D Match].[Match Id].children,([D Player].[Player Name].currentmember,[Measures].[In Time]),"F Player In Match Stat" ))
    ,[Measures].[Goals])
    Analyzing this calculated measure (the one with "nonempty") in MDX Studio shows "Function
    'Exists' was used inside aggregation function - this disables block computation mode".
    Mosha Pasumansky spoke about this in one of his posts titled "Optimizing
    MDX aggregation functions" where he explains how to optimize MDX aggregation functions containing "Filter",
    "NonEmpty", and "Union", but he said he didn't have time to write about Exists, CrossJoin, Descendants, or EXISTING (he posted this in Oct. 2008 and the busy man didn't have time since that date :P )... so anyone knows an article that continues
    on what Mosha miss or forgot? how to optimize a MDX aggregation function containing "Exists"? what can I do to achieve the same as this calculated measure but in block mode not cell-by-cell mode ?

    Sorry for the late replay.
    I didn't check if your last proposed solution is faster or not, but I'm sorry to say that it gave the wrong result, look at this:
    Player Name
    Players Team
    Goals Player Scored with Team
    A
    Team's Goals in Player's Played Matches
    Lionel Messi
    Argentina
    28
    28
    110
    Lionel Messi
    Barcelona
    341
    330
    978
    The correct result should be like the green column. The last proposed solution in the red column.
    If you look at the query in my first post you will find that the intention is to find the total number of goals a team scored in all matches a player participated in. So in the above example Messi scored 28 goals for Argentina (before the last world cup:)
    )  when the whole Argentinian team scored 110 goals (including Messi's goals) in those matches that Messi played even one minute in.

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

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

  • R12 Generate Customer Statement and email to customer automatically.

    Hi,
    Is there any standard function "Generating Customer Statement and emailing directly to customer" in R12?
    Thanks
    Dharma

    Not that I am aware of - see MOS Doc 433215.1 (Is There a Way to Email AR Statements or Dunning Letters to Customers?)
    Srini

  • Continue in a switch statement

    What is the difference between using unlabelled continue and break in a switch statement?
    Looks like there is the same effect but I didn't found anything about using continue in switch in any documentation.
    Here's a typical explanation of using switch statement:
    "If the condition in a +switch statement+ matches a case constant, execution will run through all code in the +switch+ following the matching case statement until a +break statement+ or the end of the +switch statement+ is
    encountered. In other words, the matching case is just the entry point into the case block, but *unless there's a break statement*, the matching case is not the only case code that runs"
    Is it a good practise to use continue instead of break in such case?

    Books are right again :))
    Thanks everybody who wrote here.
    As I found out continue is only for use in the loop statements. I just use continue inside both for and switch statements and that's why I thought that it's appropriate to use it inside switch. No way!! In this way continue will affect only loop, not switch statement.
    For example:
    class BreakTest {
         public static void main(String[] args) {
              BreakTest br = new BreakTest();
              br.testContinue();
              br.testBreak();
         public void testContinue() {
              int[] int_arr = { 0, 0, 0, 0, 1, 0, 0 };
              int count_in_switch = 0;
              int count_in_for = 0;
              for (int a : int_arr) {
                   switch (a) {
                   case 0:
                        continue;
                   default:
                        count_in_switch++;
                   count_in_for++;
              System.out.println("count_in_switch=" + count_in_switch
                        + " count_in_for=" + count_in_for);
         public void testBreak() {
              int[] int_arr = { 0, 0, 0, 0, 1, 0, 0 };
              int count_in_switch = 0, count_in_for = 0;
              for (int a : int_arr) {
                   switch (a) {
                   case 0:
                        break;
                   default:
                        count_in_switch++;
                   count_in_for++;
              System.out.println("count_in_switch=" + count_in_switch
                        + " count_in_for=" + count_in_for);
    count_in_switch=1 count_in_for=*1*
    count_in_switch=1 count_in_for=*7*
    In case of using continue you won't get to count_in_for++; - you'll jump to the next iteration of for loop.
    In case of using break you'll go out of switch and go to next statement, that goes after switch block

  • Switch Statement assistance

    I have to write a program that uses the switch statement and asks the user to select one of three TV models. The programs provides a description of the models. Use the switch statement, display the model chosen, the description and the price.The user should make a selection by model number: The default is "Your choice is not available!"
    I am not 100% sure that I wrote this program correctly with the switch statements and according to the guidelines set forth and would appreciate it if somebody could look it over and see if it looks correct and if not what needs to be addressed. Also, I'm getting an error when I compile (error information at the bottom of the page) and am unsure what needs to be changed to rectify this. Thanks a lot for the guidance.
    import java.util.*;
    import javax.swing.JOptionPane;
    public class javatvmodel {    /**
    * @param args the command line arguments
    static Scanner console = new Scanner (System.in);
        public static void main(String[] args) {        // Declare and initialize variables
    int model = 0;
            String modelString;
            modelString = JOptionPane.showInputDialog("This program asks the user to enter a television model number." + "\n" +
                    "The description of the model chosen will be displayed." + "\n" +
                    "\n" +
                    "Please enter the model number chosen" +"\n" +
                    "Model 100 comes with remote control, timer," + "\n" +
                    "and stereo sound and costs $1000" + "\n" +
                    "Model 200 comes with all the features of Model 100" + "\n" +
                    "and picture-in-picture, and costs $1200" + "\n" +
                    "Model 300 comes with all the features of Model 200 and" + "\n" +
                    "HDTV, flat screen, 16 x 9 aspect ratio and costs $2400");
            switch (model)
                case 100:
                    JOptionPane.showMessageDialog(null,"You chose model 100 with these features:" + "\n" +
                            "remote control, timer, and stereo sound" + "\n" +
                            "Your price will be $1000.00", "Television Selection",JOptionPane.INFORMATION_MESSAGE);
                    break;
                case 200:
                    JOptionPane.showMessageDialog(null,"You chose model 200 TV with these features:" + "\n" +
                            "remote control, timer, stereo sound, and picture-in-picture" + "\n" +
                            "Your price will be $1200.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case 300:
                    JOptionPane.showMessageDialog(null, "You chose model 300 TV with these features:" + "\n" +
                            "remote control, timer, stereo sound, picture-in-picture, HDTV, flat screen, and 16 x 9 aspect ratio" + "\n" +
                            "Your price will be $2400.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
                    break;
                default:
                    JOptionPane.showMessageDialog(null,"Your choice is not available!", JOptionPane.INFORMATION_MESSAGE); }
    Compiling 1 source file to C:\Users\Ryan\Documents\Java\Lab6_Oct7_Moran\JavaTVmodel\build\classes
    C:\Users\Ryan\Documents\Java\Lab6_Oct7_Moran\JavaTVmodel\src\javatvmodel.java:56: cannot find symbol
    symbol : method showMessageDialog(<nulltype>,java.lang.String,int)
    location: class javax.swing.JOptionPane
    JOptionPane.showMessageDialog(null,"Your choice is not available!", JOptionPane.INFORMATION_MESSAGE);
    1 error
    BUILD FAILED (total time: 1 second)
    Edited by: Nightryno on Oct 21, 2008 7:03 PM

    come on now...
    >
    String modelString = "0";
    model = Integer.parseInt(modelString);You haven't shown the input dialog yet! Move the parsing to after you've updated modelString.
    >
    >
    modelString = JOptionPane.showInputDialog("This program asks the user to enter a television model number." + "\n" +
    "The description of the model chosen will be displayed." + "\n" +
    "\n" +
    "Please enter the model number chosen" +"\n" +
    "Model 100 comes with remote control, timer," + "\n" +
    "and stereo sound and costs $1000" + "\n" +
    "Model 200 comes with all the features of Model 100" + "\n" +
    "and picture-in-picture, and costs $1200" + "\n" +
    "Model 300 comes with all the features of Model 200 and" + "\n" +
    "HDTV, flat screen, 16 x 9 aspect ratio and costs $2400");
    switch (model)
    case 100:
    JOptionPane.showMessageDialog(null,"You chose model 100 with these features:" + "\n" +
    "remote control, timer, and stereo sound" + "\n" +
    "Your price will be $1000.00", "Television Selection",JOptionPane.INFORMATION_MESSAGE);
    break;
    case 200:
    JOptionPane.showMessageDialog(null,"You chose model 200 TV with these features:" + "\n" +
    "remote control, timer, stereo sound, and picture-in-picture" + "\n" +
    "Your price will be $1200.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
    break;
    case 300:
    JOptionPane.showMessageDialog(null, "You chose model 300 TV with these features:" + "\n" +
    "remote control, timer, stereo sound, picture-in-picture, HDTV, flat screen, and 16 x 9 aspect ratio" + "\n" +
    "Your price will be $2400.00", "Television Selection", JOptionPane.INFORMATION_MESSAGE);
    break;
    default:
    JOptionPane.showMessageDialog(null, "Your choice is not available!", "Television Selection", JOptionPane.INFORMATION_MESSAGE);               

  • The new "foreach" statement and maps

    The new "foreach" statement requires an object that implements the java.lang.Iterable<T> interface.
    But why do not extend "for" for accepting objects that implements the Map interface?
    Map<String,String> m = new TreeMap<String,String>();
    for (String key, String value : m) {
         System.out.println (key + "=" + value);   
    }The current alternative
    Map<String,String> m = new TreeMap<String,String>();
    for (Map.Entry<String,String> e : m.entrySet()) {
         System.out.println (e.getKey() + "=" + e.getValue());   
    }is not so clean.

    The new "foreach" statement requires an object that
    implements the java.lang.Iterable<T> interface.Incidentally, I believe "foreach" also allows an object that is an array.
    But why do not extend "for" for accepting objects that
    implements the Map interface?I think that the use of "Iterable" is a very good idea. The interface contains just one method (iterator) and that method is inherently linked to the concept of "foreach". This means anyone can write their own class that implements Iterable, and their class can then be used with "foreach".
    If we specified that "foreach" also worked with Map (with its umpteen methods, only one of which (entrySet) is relevant to "foreach"), this would prevent people writing their own classes which iterate through pairs of values (unless those classes happened to implement Map).
    Ideally, there would be a new interface Pair<A,B> in java.lang (with getFirst() and getSecond() methods), and then if the compiler came across something like this:
        for (String str, Widget widget : items) { ... }where items is an instance of Iterable<Pair<String,Widget>>, then for each iteration, the "Pair" would be split into its component parts and stored in the variables "str" and "widget".
    Unfortunately, it would be difficult to retrofit this concept to java.util.Map, since it would require Map to introduce a new method:
    interface Map<K,V> extends Iterable<Pair<K,V>> {
        Iterator<Pair<K,V>> iterator();
    }and Map.Entry would need to extend Pair, and therefore introduce two new methods:
    interface Entry<K,V> extends Pair<K,V> {
        K getFirst();
        V getSecond();
    }Both of these changes would break huge amounts of existing code that uses Map or Map.Entry.
    Maybe one for Java 3 :)
    Geoff

Maybe you are looking for