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.
Asked
Active
Viewed 6,426 times
-9
-
2Either provide a more specific problem, or do more research on google. – Davis Broda Mar 31 '15 at 19:24
3 Answers
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
-
You're supposed to pass in a single String argument and cast each digit to an integer. See my answer below. – Malik Brahimi Mar 31 '15 at 19:28
-