03 December 2009

How to get values from command line in java

Hi friends
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. 

This example is for all type data types, because from command line all the arguments are of string type.


class getcommandtext
{
    public static void main(String[] args)
    {
        for (String s: args)
            {
            System.out.println(s);
            }
    }
}






For Numeric Command line Argument:-
If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "12", to a numeric value.


class numericargument
{
    public static void main(String[] args)
    {
        int[] firstArg =  new int[args.length];
        for (int i=0; i
            {
             try {
               
                  firstArg[i] = Integer.parseInt(args[i]);
       
                          System.out.println("Argument at index "+ i + " is " + firstArg[i]);
                 }
            catch (NumberFormatException e)
                {
                System.err.println("Argument must be an integer");
                System.exit(1);
                }
            }
    }
}


parseInt throws a NumberFormatException if the format of args[i] isn't valid. All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type.

If you run this program as
javac numericargument.java
java numericargument 1 2 3 4 5

The output will be as:
Argument at index 0 is 1
Argument at index 1 is 2
Argument at index 2 is 3
Argument at index 3 is 4
Argument at index 4 is 5