Passing command line args

I'm a beginner in java and I need to know now to write the code that takes in a randon number of numbers at the command line and stores them in an array
ie. the program is called number and when I run it, it has to take in the numbers at the command line
ie. java numbers 12 13 14 15 19 1
then these numbers are to be stored in an array
How can I do this??
Thanking you
Tom

public class Numbers {
    public static void main(String[] args) {
        // Convert to integers
        int[] param = new int[args.length];
        for ( int cnt = 0; cnt < args.length; cnt++ ) {
            try {
                param[cnt] = Integer.parseInt(args[cnt]);
            } catch (NumberFormatException nfe) {
                System.err.println("Argument " + cnt + " is not integer, using '-1'");
                param[cnt] = -1;
        // use integers ...
}

Similar Messages

  • Passing command line unicode argument to Java code

    I have to pass command line argument which is Japanese to Java main method. If I type Unicode characters on command-line window, it displays '?????' which is OK, but the value passed to java program is also '?????'. How do I get the correct value of argument passed by the command window? Below is sample program which writes to a file the value supplied by command line argument.
    public static void main(String[] args) {
    String input = args[0];
    try {
    String filePath = "C:/Temp/abc.txt";
    File file = new File(filePath);
    OutputStream out = new FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    InputStream is = new ByteArrayInputStream(input.getBytes());
    while ((len = is.read(buf)) > 0) {
    out.write(buf, 0, len);
    out.close();
    is.close();
    } catch (Exception e) {
    e.printStackTrace();
    }

    To clarify a little:
    If the "command line" means a console opened from the operating system, then the problem is that your machine's operating system can't handle the Unicode characters you want (at least, not in the console mode). If you can't configure the machine to accept Unicode on the command line, you'll have to investigate some other means of passing the argument to your app, as the other poster mentioned.

  • How to pass command line arguments to JWS app

    Hi,
    I want to pass command line arguments to my JWS application. However those arguments are dynamic (eg the username of the user who launched the app) and thus I can not use the argument tag of JNLP file. So what do I need to do in this case?
    Thanks.

    Well, if it's the username on your server systems you should probably include it in the jnlp: can pass it in the url, write once and remove jnlp href attribute, etc.., etc.. (a quick tour of this forum should suffice).
    If it's the OS username you should be able to retrieve it through system properties.
    Whatever it is, passing dynamic arguments means launching javaws through a shell or a shell script (bat if running on windows), so you won't be able to launch through autogenerated desktop and menu shortcuts.
    Anyway, you have two solutions:
    Clean one: associate an extension to your app and write those infos in a file named after that extension.
    Dirty one (always seen it work, but there's no warranty): javaws -open whateverParamYouLike yourAppURL.jnlp, will pass to your main method '-open' as args[0] and '+whateverParamYouLike+' as args[1]. I gotta admin I used it, but I had the most peculiar reason (my app needed another instance on a different JRE aware of being a secondary instance at startup time).
    Bye.
    PS: I'd really love dukes ;-)

  • Bash number of command line args....

    Hi,
    Is there a way in bash to get number of command line args ...
    atm I am using $1 but of course if you pass a command like uname -a you need two?
    wondered if there is a $<foo> that ill give number of args passed?
    EDIT looks like '$#' emmmm lets see....

    woah!!! ok thanks ..... $# gives me number of args ... will check it out
    $1 $2 > /tmp/cmd
    messy way.....

  • Include command line args in executable jar?

    Hello all,
    I'm trying to package up some software which takes 2 command line args to run (for example, java -jar prog.jar FooBar 3.14159). I'm using a utility called Jar2Exe to wrap it up into an exe (still needs JRE to run, but it's nicer packaging for distribution).
    My question is, how can I included command line arguments in the jar? Or can I? Or, are there any exe-wrapping utilities out there that will allow me to accomplish this?
    Thanks,
    -Thok

    Thok wrote:
    Hello all,
    I'm trying to package up some software which takes 2 command line args to run (for example, java -jar prog.jar FooBar 3.14159). I'm using a utility called Jar2Exe to wrap it up into an exe (still needs JRE to run, but it's nicer packaging for distribution).
    My question is, how can I included command line arguments in the jar? Or can I? Or, are there any exe-wrapping utilities out there that will allow me to accomplish this?
    Thanks,
    -ThokOkay, did some more research... It appears you can't specify command line options in a jar, but if you package it into an exe, you can--depending on what utility you use to wrap it, that is. I downloaded a free one (Launch4j) and it does the trick.
    -Thok

  • Command line args from java to C++

    Hi
    I want to pass command line arguemnts argc and argv from java to C++. I have browsed the net and most of them suggested that I declare the jni statement with jObjectarray.
    I saw an example at http://www.csc.calpoly.edu/~fouzi/crossroads/Arguments.c
    It said
    #include "/home/java/linux/jdk118/include/jni.h"
    #include "Arguments.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL
    Java_Arguments_setArgs (JNIEnv *jenv, jobject job, jobjectArray oarr)
    /* obtain the size the the array with a call to the JNI function
    GetArrayLength()                              */
    jsize argc = (*jenv)->GetArrayLength(jenv, oarr);
    /* Declare a char array for argv */
    char const* argv[128];
    int i;
    for (i = 1; i < argc + 1; i++) {
    /* obtain the current object from the object array */
    jobject myObject = (*jenv)->GetObjectArrayElement(jenv, oarr, i-1);
    /* Convert the object just obtained into a String */
    const char str = (jenv)->GetStringUTFChars(jenv,myObject,0);
    /* Build the argv array */
    argv[i] = str;
    /* print the argv array to the screen */
    printf ("argv[%i] = %s\n",i,argv);
    /* Free up memory to prevent memory leaks */
    (*jenv)->ReleaseStringUTFChars(jenv, myObject, str);
    // Increment argc to ajust the difference between Java and C arguments
    argc++;
    // Call a pipeline simulator function which uses command line arguments
    start(argc,argv);
    return;
    That is what I have where the start method is declared like this:
    void start(int argc, /* Argument count */ char argv[] / Argument strings */) {
    But I get a warning when I build the C routine. The warning arises when I am calling the start method.
    The warning says:
    f:\jni\dsaccess.c(711) : warning C4090: 'function' : different 'const' qualifiers
    f:\jni\dsaccess.c(711) : warning C4024: 'start' : different types for formal and actual parameter 2
    Can you help?
    Thanks
    Lakshmi

    1. Your array building looks bogus: Are you missing an index?
    2. You claim to be calling a "method". Are you? Or is it a subroutine?

  • Wrong to process command line args in a loop?

    I tried to process my command line args like this:
    int[] rgb = {0,0,0};
              for(int i=1;i<3;i++)
                   rgb[i-1] = Integer.parseInt(args);
    I enter six args where args 1 to 3 are ints and not zero, but rgb[2] always ends up being zero. I had to do away with the loop and write out three assignment statements, but if I had ten or more args that would be a headache! Does anyone know why this is happening? I'm using JDK 1.3.1_15.

    for(int i=0;i<3;i++)
       rgb[i] = Integer.parseInt(args);
    Look closely and make sure you understand the differences between my code and yours:
    * i starts at 0, not 1
    * rgb uses i for index, not i - 1.
    Why would you have rgb using i -1 and args using i?
    Now, if you have an arg [i]before the RGB args, then it would make sense for args' index to be different than rgb's. In that case, you might have i-1 and i, or i and i+1, etc. depending on how you structure your loop.
    The main problem is that you had i=1; i<3, which will go through the loop body for i=1 and i=2 only. Make sure you understand why.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Command line args

    I have this program and I need to use command line args which
    will print ell . this program does this but I am using
    substring instead of command line args.
    public class h11 {
    public static void main (String [] args ) {
    String greeting = "Hello";
    String h11 = greeting . substring (1, 4);
    System.out.println( h11);
    output: ell
    Anyone..

    First off, the index of characters in a String is 0 based so in the string "Hello" you have the following;
    char 0 = "H"
    char 1 = "e"
    char 2 = "l"
    char 3 = "l"
    char 4 = "o"
    String.substring(start, end) is first inclusive and last exclusive so the parameters (1, 4) would return characters 1, 2 & 3 but not 0 or 4.
    To get the whole word Hello (not withstanding that that's the entire string) you would want greeting.substring(0,5) however that would generate an index out of bounds error because 5 isn't a valid index for that string. So, here's a small sample program to show how to do what I think you're after.
    public class ParmsTest{
         public static void main(String[] args){
              if( args.length > 0 ){
                   String parm = null ;
                   int end = 0 ;
                   int start = 0 ;
                   for( int i=0; i< args.length; i++ ){
                        parm = args[i] ;
                        if( parm.length() > 4 ){
                             end = 4;
                        else{
                             end = parm.length() - 1 ;
                        if( end > start ){
                             System.out.println( parm.substring(start, end) ) ;
                        else{
                             System.out.println( "Nothing to get" ) ;
              System.out.println( "Finished processing parameters" ) ;
    }It's a bit more complicated than your sample, but it also checks to see if there were any parameters, and it checks to see if the length we're trying to get is valid. Lastly it checks to see if there was anything to get before trying to print it. If it doesn't find anything to print it prints a message saying so.
    Here's the question I have for you. Why? Why did I go to this trouble?

  • Is it possible to pass command line as variable.

    Hi to all,
    I have an application(java based) which upon execution asks for database name after selection thru file dialog, it spawns dos window and executes batch file (and the batch file contain command line java programm).
    Now my question is how can i pass the database name to this spawned java application in dos prompt.
    Anybody's suggestion is welcomed.
    Regards
    Khizer

    Two ways, as a property or as an argument.
    You can set it as a property like this using the -D option:
    java -Ddatabase.name=MyDatabase ....
    Then you can read it from the application as
    System.getProperty("database.name");
    Passing it as an argument goes like this:
    java ... MyMainClass MyDatabase
    and read it as
    public class MyMainClass {
      public static void main(String[] args) {
        if (args.length == 1) {
          System.out.println("Database name is: "+args[0]);
        } else {
          System.out.println("Usage: java ... MyMainClass <database name>");
    }

  • How to pass command line arguments to Web Start appclient?

    Hi,
    I would like to pass arguments to appclient, but "javaws" unable to do that.
    Do I have to overwrite the JNLP? I use Sun Appserver 9.0, it creates JNLP on the fly!!!
    Please help, thanx!
    MB

    Hi, MB.
    If you are talking about the automatic Java Web Start support for launching app clients in GlassFish, you can pass the equivalent of command line arguments using the query string of the URL you use to launch the app client.
    Briefly, use
    http://host:port/client-path?arg=first-arg&arg=second-arg& ...
    specifying the argument values in the order that you want them passed to the client.
    The GlassFish server will do the right thing and generates the correct JNLP so your arguments are passed to the app client.
    The GlassFish developer's guide http://glassfish.dev.java.net/nonav/javaee5/docs/AS91DG.pdf discusses this and all aspects of the Java Web Start support. You can also take a look at this blog entry http://blogs.sun.com/quinn/entry/command_line_arguments_and_properties that focuses on how to pass arguments.
    Since this technique deals with argument passing in the URL, it works no matter how you launch the app client: a URL in a browser, the javaws command, etc.
    - Tim

  • How to pass command line parameters During server start up

    Hi,
      I am trying to use Net Beans profiling tool.On the server side i required to pass a command line option to enable remote profiling.
    Regards,
    Kiran.

    Hi, MB.
    If you are talking about the automatic Java Web Start support for launching app clients in GlassFish, you can pass the equivalent of command line arguments using the query string of the URL you use to launch the app client.
    Briefly, use
    http://host:port/client-path?arg=first-arg&arg=second-arg& ...
    specifying the argument values in the order that you want them passed to the client.
    The GlassFish server will do the right thing and generates the correct JNLP so your arguments are passed to the app client.
    The GlassFish developer's guide http://glassfish.dev.java.net/nonav/javaee5/docs/AS91DG.pdf discusses this and all aspects of the Java Web Start support. You can also take a look at this blog entry http://blogs.sun.com/quinn/entry/command_line_arguments_and_properties that focuses on how to pass arguments.
    Since this technique deals with argument passing in the URL, it works no matter how you launch the app client: a URL in a browser, the javaws command, etc.
    - Tim

  • Environmental variables as command line args

    Hello, all,
    I would like to pass an environmental variable as a command line argument for a java program.
    Example:
    java MyClass $MY_VARIABLE
    However, it actually passes "$MY_VARIABLE", and not the value of MY_VARIABLE. I know that I can use java -D(MY_VARIABLE=SOMETHING) and get it using System.getProperty ("MY_VARIABLE");
    However, I would prefer it the first way, actually passing the variable inside command line. Is there a way to do this?
    Thank you,
    Elana

    Nevermind... Error in my code... It works
    Thank you

  • How to Pass Command line arguments to an exe created in LV8.0

    Hi Friends,
    I have Created an exe in LV8.0, which accepts the Folder path as input and executes.
    I want to call this exe passing the parameter (i.e folder path in my case)  from the command line argument. How to pass arguments to the exe ?
    Generally we may be having different types of input parameters to a vi like numeric control, string, boolean etc..If we create an exe that needs three input parameters among which one is boolean, other is string and third is a numeric value.
    How to pass these different types of input controls to the exe as parameters in command line at the same time?
    Thanks and Regards,
    SODLB

    I don't have any experience with the 8.x application builder, but the 7.x one has a checkbox for passing the arguments to the executable.
    As for reading them, there should be an example in the example finder (Help>>Find Examples) which shows how to do this. If you want to pass multiple parameters, I suggest you use a structure similar to NAME=VALUE, so that you can parse each element to find the = and then use a case structure to decide what to do with the parameters. This allows your users to enter or not enter any of the switches.
    Try to take over the world!

  • How to pass command line options?

    I know that command line options contrary to command line data arguments start with a prefix that uniquely identifies them.
    I write an application that will copy files from one folder to another. It should be launched with the syntax as follows:
    c:>java my.app.DirectoryScannerConsole
    c:>scan ?input ?C:/test/in? ?output ?C:/test/out? ?mask ?*test*.xml? ?waitInterval 60000 ? includeSubfolders false ?autoDelete true
    c:>exitSo after launching we have two commands: 'scan' and 'exit'. What should I make in my program to be able to invoke these commands in such a manner?
    Edited by: Exaserge on Nov 8, 2008 10:38 AM
    Edited by: Exaserge on Nov 8, 2008 10:40 AM

    Maybe try using Scanner to read in the line of input, then break the line into an String array, then comparing the Strings in the array.
    Something like...
    public static void main(String args[])
       Scanner in = new Scanner(System.in);
       String line = in.readLine(); //read in an entire line of input
       String words[] = line.split(" "); //split that line wherever there is a space
       while ( !(words[0].equals("exit")) ) //if they haven't typed in exit
          if (words[0].equals("scan")
              if(words[1].equals("-input"))
                 String inputFile = words[2]
              //etc.
          line = in.readLine();
          words = line.split(" ");
    }I haven't tried to compile it or anything, so it may not be syntactically correct, but you should get the idea.
    Edited by: chickenmeister on Nov 8, 2008 1:02 AM

  • About Command line args

    there is command line argument fir integer like Integer.parseInt(args[0]); can we write same for "char" and" double" also like "Double.parseDouble" or else......

    this has nothing to do with command line arguments
    but yes, all the primitive wrapper classes can parse back their primitive
    Learn to use the API, it's your friend
    http://java.sun.com/javase/6/docs/api/

Maybe you are looking for

  • How to read in a text file of race lap times....

    How do i read in a text file containing lap times from a race for one driver? I have the times down 1 column and look like this. I then want to add the times up to get a total race time. I have been looking at the Calendar class and the simpleDateFun

  • Xws-security web service

    Hi guys, I finished running the xws-security samples in the JWSDP, and start trying to build a web services with xws-security feature. I copied the "config" folder containing config xml files, and the build.properties file from the sample to my own n

  • Install Base Table relationship

    Hi Expert, Could you plz explain me how to relate Install Base tables so that I can able to show data like the component structure and then their corresponding order, contract etc thanks

  • Helpme I have error when I try connect from struts  to web service

    helpme I have error when I try connect from struts to web service using basic authentication . the error message is [SOAP Exception: fault code= SOAP-ENV Protocol; msg=Unsupported response content type "text/html" must be "text/xml"; ] Response was <

  • CS3-Font issue spaces appears as blocks

    I have a user that with certain types of fonts (TrueType Regular) are having a problem. Spaces (space character) are appearing as blocks. This user has a PC that is exactly like the other two next to her and those two are working perfectly. All are W