Create a class named SumOfArgs
that will print out the sum of all integer arguments found on the command line. It should have a main() method so the class can be run. Anything that is not an integer should be skipped (should not contribute to the sum). It should print out only the sum (nothing else!). No error messages can be printed out (no matter what the command line args look like). Examples of what your class should do when run:
|
import java.util.Scanner;
public class SumOfArgs {
public static int numSum(String str)
{
if(str==null)
{
return 0;
}
char[]charArr=str.toCharArray();
int res=0;
int num=0;
boolean posi=true;
int cur=0;
for(int i=0;i<charArr.length;i++)
{
cur=charArr[i]-'0';
if(cur<0||cur>9)
{
res+=num;
num=0;
if(charArr[i]=='-')
{
if(i-1>-1&&charArr[i-1]=='-')
{
posi=!posi;
}else{
posi=false;
}
}else{
posi=true;
}
}else
{
num=num*10+(posi?cur:-cur);
}
}
res+=num;
return res;
}
public static void main(String[]args)
{
Scanner scanner=new Scanner(System.in);
String str=null;
str=scanner.nextLine();
System.out.println(numSum(str));
}
}