how to pass Command line arguments in java [duplic

2019-03-07 08:50发布

问题:

This question already has an answer here:

  • Java Command line arguments 9 answers

How to accept two digit number as command line argument and print the sum of its digits. If two digit number is 88 output will be 16. Here my task is to dont use conditional or looping statements.

回答1:

Just use the first string passed from the command line adding the casted integers of each digit.

public class Test
{
    public static void main(String[] args)
    {
        int a = Integer.parseInt(args[0].substring(0, 1));
        int b = Integer.parseInt(args[0].substring(1, 2));

        System.out.printf("Sum: %d", a + b);
    }
}


回答2:

Your java class should have a main method as such

public static void main(String[] args) {
    ....YOUR CODE....
}

When you compile and run your class, all command line parameters will be contained in the args method parameter. You can read that array to get your data and do what you want with it.



回答3:

The main method in a java class takes String array as an argument and you can access your command line arguments using array index, for example

public class Test {
    public static void main(String[] args) {
        // check for an empty array is recommended here
        int a = Integer.parseInt(args[0].substring(0, 1));
        int b = Integer.parseInt(args[0].substring(1, 2));
        System.out.println(a+b);
    }
}