-
Confused
Hi, I have just started learning Java and I have a question.
Using Eclipse, I am trying to run this:
Code:
public class AddNumbers{
public static void main(String[] args) {
System.out.println("Addition of two numbers!");
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
But when I run it, I get the error:
Code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at AddNumbers.main(AddNumbers.java:4)
I am confused as to why this is happening, can anyone help?
I know it's probably going to be some stupidly obvious thing that i'm forgetting, but i'm just a noob! :P
Thanks!
-
You have to run this code with two command line parameters. But seems to me, you don't have use any.
-
use args.length to check had user input any thing
-
Include arguments
When you run the program, you have to include two arguments (the numbers you want to add). For example, if you want to add 3 & 4, you would specify:
Code:
java AddNumbers 3 4
Luck,
CJSL