public class Sum {
public static void main(String args[])
{
int x,y,s;
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
s=x+y;
System.out.
You need to pass the command-line arguments:
java Sum 0 1
It's also recommended to check length in this case:
int x,y,s;
if(args.length>=2){
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
s=x+y;
System.out.println("sum " +s);
}
And considering the intent of the program, you might want to loop the args[]
array directly, and sum all numbers instead of just the first 2:
int total = 0;
for (int i = 0; i < args.length; i++) {
total = total + Integer.parseInt(args[i]);
}
System.out.println("Total: " + total);
Command-line: java Sum 1 2 3 4 5
results in Total: 15
When you run this from the commandline, you need to pass in your values for x and y:
java Sum 4 5
If you are running this from eclipse, you need to set it up to pass these arguments in every time you hit the green "run" button.
Eclipse command line arguments
If you don't pass anything in, then the array "args" will be empty. Then you try and access the first element in the array, but since it is empty, this throws an ArrayIndexOutOfBoundsException.