Addition of Numbers by Using Command Line Argument in Java
HERE IS THE CODE:
- class Addition
- {
- public static void main(String [] args)
- {
- int i,sum=0;
- for(i=0;i<args.length;i++)
- {
- sum=sum+Integer.parseInt(args[i]); // main line of the program.
- }
- System.out.println("the sum of the command line arguments="+sum);
- }
- }
If you only write
sum=sum+args[i];
then sure some error will come. see the error in the below.....
error: incompatible types: String cannot be converted to int
sum=sum+args[i];
This will come in the cmd.
Because command line arguments are string type and sum variable(name in my code) is a integer type variable .So if we add a Integer type and a String type value then surely give a error.
So what can we do??
Answer: convert the String type value to the corresponding Integer type value.
But how can we do??
Answer: Use of Integer.parseInt() method. This is the method of the wapper class(Integer).This is a static method .so without creating a object of the Integer class ,we can invoke the Integer.parseInt() method.
Helpful program
ReplyDelete