Passing arguments

Our teacher just taught us about methods and passing arguments, etc. I have been over our text book and I don't quite understand how it works. Any help?
PROBLEM:
?     Write a program with four methods. One is the main method. The other three are named startMessage, message, and finishMessage.
?     Within the startMessage method, place code to print out the message ?The program has started.?
?     Within the message method, place code to print out any message that is passed, as a String, into the method using a String parameter named output.
?     Within the finishMessage method, place code to print out the message ?The program is done.?
?     When the program begins call the startMessage method.
?     Then display the following dialog box:
"Enter a message:"
?     Using a While loop, respond to the user?s input appropriately:
     If the user presses OK display whatever the user has entered by calling the message method with the user?s input as the argument. Continue to display the dialog box and display the user?s input until they press Cancel.
     When the user presses Cancel stop showing the dialog box, and do not display what the user has entered.
?     After the user presses Cancel, and before the program terminates, call the finishMessage method.
?     Terminate the program.
here is what I have so far:
public static void main(String[] args) {
          startMessage();
          String userMessage = JOptionPane.showInputDialog("Enter a message:");
          while (userMessage != null){
               message(userMessage);
               JOptionPane.showMessageDialog(null, "Here is message" + message());
               userMessage = JOptionPane.showInputDialog("Enter a message:");
          finishMessage();
          System.exit(0);
     public static void startMessage(){
          JOptionPane.showMessageDialog(null, "The program has started.");
     public static String message (String output){
          output = userMessage;
          return(output);
     public static void finishMessage(){
          JOptionPane.showMessageDialog(null, "The program is done.");
}what's giving me the problem is the message method; I can't figure out how to pass whatever they put in the userMessage variable to the message method

I am stuck here
PROBLEM:
?     Change your C6E2 class by adding a new method called getNumberInput. This method will be used to get a number input from the user, replacing the lines of code in the main method that were previously used. You will need to call this method twice from the main method, prompting for the first and second numbers in turn.
?     Write the method so that the prompt displayed in the input dialog box is passed through an argument.
?     The return type of this new method will be a double.
I can't figure out how to pass the input paramater correctly, any help?
public static void main(String[] args) {
          double num1 = 0;
          double num2 = 0;
          double addResult = 0;
          double subtractResult = 0;
          double multiplyResult = 0;
          double divideResult = 0;
          double input1 = getNumberInput(num1);//this is where I am stuck
          double input2 = getNumberInput(num2);
          addResult = add(num1, num2);
          subtractResult = subtract(num1, num2);
          multiplyResult = multiply(num1, num2);
          divideResult = divide(num1, num2);
          JOptionPane.showMessageDialog(null, addResult);
          JOptionPane.showMessageDialog(null, subtractResult);
          JOptionPane.showMessageDialog(null, multiplyResult);
          JOptionPane.showMessageDialog(null, divideResult);
          System.exit(0);
     }//main
     public static double getNumberInput (double input){
          double output = 0;
          Double.parseDouble(JOptionPane.showInputDialog("Enter a number:"));
          return output;
     public static double add (double term1, double term2){
          double result = term1 + term2;
          return result;
     }//add
     public static double subtract (double term1, double term2){
          double result = term1 - term2;
          return result;
     }//subtract
     public static double multiply (double term1, double term2){
          double result = term1 * term2;
          return result;
     }//multiply
     public static double divide (double term1, double term2){
          double result = term1 / term2;
          return result;
     }//divide
}//class

Similar Messages

  • How to run a java class from a shell script with passing arguments

    hi,
    I have a jar with all the required classes. I was using ant to run the classes i needed.
    But now i want to use a shell script to run the class, also the class accepts some arguments so when script is run it should accept arguments.
    So can any one tell me how to set class paths, jar location and call the required class from shell script or batch file with passing arguments to it.
    Thanks in advance.

    Let's say that the order of arguments is as below
    1. Jar file name
    2. Classpath
    Your shell script would look like this
    java -cp $CLASSPATH:$2 -jar $1 I am assuming that your jar file has the required main-class entry in its manifest. Note that $1...$9 represent the arguments to this shell script.
    The same goes for a batch file
    java -cp %CLASSPATH%;%2 -jar %1

  • How to pass argument to the Java Plugin JVM w/o using the Control Panel?

    I want to deploy an applet to be loaded by the Java Plug In
    and fix some settings of its Java Virtual Machine.
    The JPI Control Panel offers two ways to pass arguments to the JVM,
    none satisfactory.
    1. while interactive via the Control Panel Window.
    This cannot be a solution for a deployed applet.
    or
    2. by editing the system generated file that stores
    the settings of the Plugin Control Panel, using a property
    named javaplugin.jre.params.
    The problem with this method is that if forces to access
    and edit this property file which is stored at various locations
    depending the client platform. Then, it may collide with other
    settings for other applets.
    Is there a way to pass the arguments to the JVM
    from within the html file?
    Has anyone found a solution to this question?
    JPS

    I am interested in this issue as well.
    Did anyone find a reliable way to specify the runtime parameters that should be used by the Java Plug-in in order to execute a given Java applet?
    I believe a good place to specify these runtime parameters would be the applet's JAR manifest: only digitally signed applets should be able to set the desired runtime parameters...
    Any comments / suggestion would be greatly appreciated.
    Regards,
    Marco.

  • How to pass argument in manifest file

    Hi,
    I want to pass argument to main class in jar. Is there any option in manifest file.

    Hmm..
    Seems that my sentence above isn't so correct.
    It possible to add custom attribute: value pairs into manifest file and
    read it later from Java class.
    Here is code sample:
    public class ManifestTest {
        public static void main(String[] args) {
            try {
                java.util.jar.JarFile jar = new java.util.jar.JarFile(System.getProperty("java.class.path"));
                for (java.util.Iterator it = jar.getManifest().getMainAttributes().keySet().iterator();it.hasNext();) {
                    Object curKey = it.next();
                    System.out.println("key: " + curKey + ", value: " + jar.getManifest().getMainAttributes().get(curKey));
            } catch (Throwable t) {
                System.out.println("exception occured: " + t);
    }

  • How can I pass arguments to a TestStand sequence with LabWindows 6 ?

    Hi
    I have created sequences in a TestStand file.
    I want to program a sequence with Labwindows 6 which would call all these existing sequences (containing parameters).
    I don't have any problems to create the steps "SequenceCall" but i don't know how to pass arguments to the sequences with the TS API.
    I have used the look-up strings "TS.SData.SFPath", "TS.SData.SeqName", "TS.SData.ThreadOpt" to program the sequence file / sequence and the multithread option. But now how to program the arguments passing ? I think there is something with the lookup string "ST.SData.ActualArgs"...
    Thank u very much for any help

    I'm not sure if you want to pass values from TestStand to LabWindows or if you want to pass values in TestStand from a sequence call step to a called sequence.
    To get TestStand variables from LabWIndows, use the following function:
    tsErrChk (TS_PropertyGetValNumber(testData->seqContextCVI, &errorInfo, "Locals.StartPoint", 0, &dStartPt));
    iStartPt = (int)dStartPt;
    The TS_PropertyGetValNumber gets the TestStand variable Locals.StartPoint and puts it into the LabWindows variable called dStartPoint. Numbers to and from Test Stand are always a double type. The next line converts it to an integer.
    To put a LabWindows value to TestStand, use TS_PropertyPutValNumber.
    To pass values from a sequence call step to a called sequence, create variables in the Parameters t
    ab on your main sequence. Create same variables on the Parameters tab of the called sequence. In main, specify module to be called in calling step. There is a paramters section on the Edit Sequence Call dialog box which appears. Check the Use Prototype of the Selected Sequence box. You can then list all the parameter variables in the parameters section.
    Hope this is what you want.
    - tbob
    Inventor of the WORM Global

  • Passing Arguments in a Multiple JFrame project

    I am trying to pass Arguments from MainApp.java to SubApp.java.
    Is there someone that have an example or fix the sample program included?
    tks a lot
    sage49
    I based my program on the following 2 programs that I got from this forum!!
    The following is the MainApp.java
    import javax.swing.*;
    import java.awt.event.*;
    class MainApp extends JFrame {
        MainApp() {
            super( "Main Application" );
            JButton button = new JButton( "Show Sub Application" );
            button.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
    //  need to pass a string to SubApp in the following line
                    JFrame app = new SubApp();
                    dispose(); 
            getContentPane().add( button );
            setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            pack();
            show();
        public static void main( String[] args ) {
            MainApp app = new MainApp();
    }The following is the SubApp.java
    import javax.swing.*;
    import java.awt.event.*;
    class SubApp extends JFrame {
    // need to accept a String as Arguments
        SubApp() {
            super( "Another Application" );
            JButton button = new JButton( "Show Main Application" );
            button.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    JFrame app = new MainApp();
                    dispose();
            getContentPane().add( button );
            setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            pack();
            show();
        public static void main( String[] args ) {
            SubApp app = new SubApp();
    }

    Hi,
    I have done what you suggested, Now I get an error on the subApp on the main.
    see What I tried in the code.
    MainApp.java
    import javax.swing.*;
    import java.awt.event.*;
    class MainApp extends JFrame {
        MainApp() {
            super( "Main Application" );
            final String a ="this is the string";
            JButton button = new JButton( "Show Sub Application" );
            button.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    JFrame app = new SubApp(a);
                    dispose(); 
            getContentPane().add( button );
            setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            pack();
            show();
        public static void main( String[] args ) {
            MainApp app = new MainApp();
    }The SubApp.java
    import javax.swing.*;
    import java.awt.event.*;
    class SubApp extends JFrame {
            private String mystring;
            SubApp(String mystring) {   
            super( "Another Application" );
            this.mystring = mystring;
            JButton button = new JButton( "Show Main Application" );
            button.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    JFrame app = new MainApp();
                    dispose(); 
            getContentPane().add( button );
            setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            pack();
            show();
        public static void main( String[] args ) {
           // tried    =    SubApp app = new SubApp(mystring);
           // tried    =    SubApp app = new SubApp(a);
           // tried    =    SubApp app = new SubApp(String a);  
           // tried    =    SubApp app = new SubApp(String);                 
            SubApp app = new SubApp();                // this is the line I get the error
    }I get the following error:
    Cannot find Symbol
    symbol  : constructor SubApp()
    location: class SubApp
            SubApp app = new SubApp();Tks a lot
    sage49

  • Creating pocess intance of a different process and passing arguments

    Creating Process instance of a different process:
    I have two different process: Main_Flow (id: MainFlow) and Second_Flow (id: SecondFlow). In the first process I am reading a csv file. Each line of the file has four columns. After reading each line I have to initiate Second_Flow and pass the read data from the file. (Pls find the code below for the whole process):
         fileReader = FileReader(arg1 : fullFileName);//filename is of file type and have file name and path
         Java.Io.BufferedReader reader = BufferedReader(arg1 : fileReader);
         String str;
         int countLines = 0;
         while ((str = reader.readLine()) != null)
              strColumn = str.split(delim : ",");
                   int ColumnCnt = 0;
                   while (ColumnCnt < 4)
                        //defining variables
                        String appNo;
                        String custNo;
                        String loanAmm;
                        String loanDate;
                        //logMessage("Value at Column: " + ColumnCnt + " is " + strColumn[ColumnCnt]);
                        if (ColumnCnt == 0)
                             arrLoanData["appNo"] = strColumn[ColumnCnt];
                        else if (ColumnCnt == 1)
                             arrLoanData["custNo"] = strColumn[ColumnCnt];
                        else if (ColumnCnt == 2)
                             arrLoanData["loanAmm"] = strColumn[ColumnCnt];
                        else if (ColumnCnt == 3)
                             arrLoanData["loanDate"] = strColumn[ColumnCnt];
                        arrLoanData["descriptionArg"] = "AutoInstance: " + formatTime('now', timeStyle : Time.SHORT);
                        arrLoanData["genByArg"] = "Automatic";
                        ProcessInstance.create(processId : "/SecondFlow", arguments : arrLoanData, argumentsSetName : "BeginIn");
                        ColumnCnt = ColumnCnt + 1;
              countLines = countLines + 1;     
    (“The code is in Java and not in PBL”)
    I have to pass appNo, custNo, loanAmm and loanDate as the arguments. The Argument will be of Any[String] type. The argument set name of Second_Flow is “BeginIn”. But I am not getting anything in Second_Flow.
    What can I do in the argument mapping of begin of Second_Flow to get the passed argument (array)?

    the argument 'arguments' for the method ProcessInstance.create receives a map of the arguments that the 'argumentSetName' argument set will receive.
    so for example if your second flow has 2 arguments, String name, Decimal value and String[] content your method invocation would be:
    ProcessInstance.create(processId : "/SecondFlow", arguments : {"name": strNameFromCsv, "value": valueFromCsv, "content": ["a","b","c","d"]}, argumentsSetName : "BeginIn");

  • How to pass argument in main function ?

    How to pass arguments in main function of one class from another class ?
    I don't want to pass argument from command prompt.
    I want to try something like this -
    class Test{
    public static void main(String args[]){
    for(int i=0;i<args.length;i++)
         System.out.println(args);
    class Fun{
    public static void main(String args[]){
         Test t=new Test("Hello","good bye");
    when i run Fun class it gives error.
    Suggest me how can i do that.

    In Fun class main method does not take arguments that is fine. In Test class instead of main method you can have constructor to take input parameters as suggested by BalusC
    However, if you want to make your existing code work, you can call (though not appropriate) main() method of Test class from main() method of Fun class (As main() method is static object is not required to invoke this):
    Test.main(new String[]{"Hello","good bye"});Here is your code:
    class Test{
    public static void main(String args[]){
    for(int i=0;i<args.length;i++)
    System.out.println(args);
    public class Fun{
    public static void main(String args[]){
    //Test t=new Test("Hello","good bye");
    Test.main(new String[]{"Hello","good bye"});
    } Thanks,
    Mrityunjoy                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Passing arguments to a custom component in the constructor

    I would like to know if it is possible to pass arguments to a
    custom component in the constructor when I'm instantiating it
    within Actionscript. I've not seen anyone do this, so at the moment
    I have a couple of public properties defined on the custom
    component and then do the following:
    var myComponent:TestComponent = new TestComponent();
    myComponent.propertyOne = true;
    myComponent.propertyTwo = 12;
    etc.
    Whereas I'd like to do something like:
    var myComponent:TestComponent = new TestComponent( true, 12
    Any ideas if this is possible?

    Another approach as opposed to creating init function is to link symbol with autogenerated class (just assign it a class but do not create *.as file for it) and use it just as graphical view with no functionality (well only MovieClip's functionality).
    ViewClip.as
    public class ViewClip extends MovieClip {
        public var view:MovieClip;
        public function ViewClip(){
            this.view = instantiateView();
            this.addChild(view);
        protected function instantiateView():MovieClip {
            return new MovieClip();
    Circle.as
    public class Circle extends ViewClip {
        public function Circle(scaleX:Number, scaleY:Number) {
            super();
        override protected function instantiateView():MovieClip {
            return new ClassView();

  • Pass arguments to JSF tag attributes like id oder value

    Hi!
    I started with JSF some weeks ago and have some questions that i could not find in FAQ or tutorials.
    My page structure uses some <jsp:includes>. Each included page uses JSF.
    The structure is (example - users):
    Users.jsp
    |
    |(incl)
    |
    Mainpage.jsp (=Framework)
    |
    |(incl)
    |
    Browser.jsp (=Table)
    In "Users" all specific data is set. In "Browser" there is a <h:form> tag and a <h:dataTable> tag.
    The result should be a simple table with users inside.
    So I want to pass arguments to those sub-pages.
    1) -> form-ids as parameter:
    <h:form id="#{sessionScope.formName}">
    ... does not work, because ids have to start with a character or "_".
    formName is set as followed:
    session.setAttribute("formName", "form_users");
    2) ->beans as parameter:
    <h:dataTable id="browser_table_#{sessionScope.id}" styleClass="browser_table"
    var="user" value="#{sessionScope.user_list}">
    ... does not work. "id" is requested to be a static value and "value" can't find the bean by this string.
    user_list is set as followed:
    session.setAttribute("user_list", "UserListBean.users");
    (UserListBean.users is an ArrayList)
    Is there an error in my thinking? Or is there a way to pass arguments as i want?
    Thanks!

    sorry ... mistake in topic: "oder" = "or" of course :)

  • RMI Codebase Passing Arguments

    I'm new to RMI and Java.How do you pass arguments using serialization in RMI? I'll be passing the arguments from a servlet. for example if i want to pass a string object from a servlet to the calling client service. Thanks

    Can you please provide me with a better direction in terms of developments (i.e examples)? thank you

  • How to execute adobe air app & pass argument from Flex ?

    Helo everyone,
    May i ask a question, How to execute adobe air app & pass argument from Flex ?
    Thanks in advanced.
    Jacky Ho.

    Hello Jacky,
    You can find an example here
    http://spreadingfunkyness.com/passing-parameters-to-adobe-air-at-startup/

  • Passing arguments to VBScript Program Object - Without WScript.Arguments?

    I am trying to create a program object with a VBScript that will change the name of a PDF created by a scheduled report. I need to be able to tack on the string "OH_2010_Qtr_1" (or whatever state - OH is used as an example) before the file extension - the VBScript creates that string based on the date the report is run. I want to be able to pass parameters to this script but when I try to do so I get the error "Variable is undefined 'WScript'" when trying to run the program object. I tried creating a batch file that would pass in the parameters and I get a generic error.
    How can I pass arguments to my VBScript? The arguments are necessary because this is for multiple instances of the same report, run for different states.

    For VBScript Program Objects, some injected objects:
    For Each arg in Script.Args
        ' Do something interesting with String arg here
        Script.Writeln(arg) ' Output to stdout
    Next
    and
    ' Get InfoStore
    Set infoStore = Session.Service("", "InfoStore")
    Sincerely,
    Ted Ueda

  • Problem passing arguments with air.swf

    I'm attempting to launch my AIR application using
    launchApplication() in air.swf. I'm having problems passing
    arguments to my application due to what appears to be some
    restriction in allowed characters. To get around this, I've even
    tried URL encoding and Base-64 encoding my arguments to make them
    more friendly, but it's still failing:
    Error: Invalid argument: PG5vIGlkZW50aWZpZXI+
    at AIR$/escapeArguments()
    at AIR/launchApplication()
    at
    adlm_launcher/onDownloadClick()[E:\adlm\launcher\src\adlm_launcher.mxml:181]
    It seems that any kind of punctuation is not allowed in
    arguments. URL encoding them doesn't work either because the % is
    rejected. Is there any other way around this?

    Yes; it's a security restriction. Browser invocation require
    process creation, and many process creation APIs giving special
    meanings to certain characters. Letting those characters through
    has in the past been a source of security vulnerabilities. While we
    also try to avoid using APIs with this behavior, extra layers of
    defense are also good.
    I think + and / may actually be safe choices; you make a good
    point that they're useful for Base64. If you could submit a feature
    request at www.adobe.com/go/wish, we'll definitely consider it.
    Another option, btw, is to use the LocalConnection API to
    pass data between the web page and your application once your app
    is launched. LocalConnection has fewer restrictions on the data
    passed.

  • Pass arguments in a applet

    i know when you run a prog you could pass arguments, can i do with my applet.. like take a textbox in my html page?????

    thx man you're nice
    yes. you can do that. That is actually an <HTML>
    syntax question. Following might help
    <applet code="Chat" width=600 height=400>
    <param name=host value="somewhere.hotwired.com">
    <param name=port value="2323">and on the java side look at the APi and under Applet
    class look for getParameter() method

  • Can we pass arguments to JNLP?

    I am new to JNLP and want to know can we pass arguments to JNLP?
    If yes where I can find the info abt it?

    Dolda2000 wrote:
    Will that really work well, though? As far as I can tell, the JNLP client will try to refetch the JNLP file when launching the Java program (reasonable enough). If I were to include
    information from that is only available via the user's web brower's session, I would not be able to recreate that data when the JNLP client tried to refetch the JNLP file.If you're worried about that why not use a user specific cookie?
    Your CGI script can check for/generate/pass one along with the XML stub.
    As far as I know the JNLP is stateless. It loads once,
    the information is cached, your application gets run....
    I already do this with <applet> tags (not currently JNLP) to identify returning users
    and pass dynamic parameters to applets. I will be updating to JNLP after a rewrite
    of some code.
    P

Maybe you are looking for

  • My iphone Mail wont let me reply to emails

    Nor can I generate a new email. Was fine until yesterday. Doing it across Gmail and Hotmail.

  • Linked .eps files cause error in InDesign CS5

    I upgraded to CS5 about 2 weeks ago and all is well except: In 2 files so far, some (but not all) of the links to .eps files (within anchored image frames) show up as gray rectangles with crossed diagonal lines. In addition, I get the following error

  • A question for the copyright for the swing tutorial

    Hello, I'm using (verbatim) the http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ColorEditor.java from the swing tutorial that is from the same named book. What should i do in order to not violate the attached copyright?

  • Vampire Apps

    Hi, I have a 5 year old Macbook running Mac OS X version 10.7.5. I recognize that this is at least two versions behind the current Mavericks. I do not plan o upgrade, fo even though the latest version is supported on my MacBook, that great of a dispa

  • ADF Taskflow Transaction Management Pattern

    We have a project that consumes public common taskflows from a shared library. How should we define the transaction management of these public common taskflows? Who is respondsible for the transaction management? I am able to understand the various t