how to pass Command line arguments in java [duplic

2019-03-07 09:20发布

This question already has an answer here:

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.

3条回答
爷的心禁止访问
2楼-- · 2019-03-07 09:22

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);
    }
}
查看更多
对你真心纯属浪费
3楼-- · 2019-03-07 09:28

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-03-07 09:34

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);
    }
}
查看更多
登录 后发表回答