-9

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.

user28536
  • 123
  • 2
  • 9

3 Answers3

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);
    }
}
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

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.

Raymond Holguin
  • 1,050
  • 2
  • 12
  • 35
0

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);
    }
}
Kishore Kirdat
  • 501
  • 4
  • 9