开发者

Using args.length instead of nums.length

I need to calculate the number of integers in an arg as well as calculate the average. Currently my code is the following with the problem in bold.

int count = args.length;
    System.out.println(count);

    int sum = 0;
    for (int i = 0; i < args.length; i++)
        **sum += args[i];**
            **//  The operator += is undefined for the argument type(s) int, String**

 开发者_StackOverflow社区   double average = ((double) sum) / args.length;


}

How do i make it so that the average is calculated using integers in args.length?


your args variable is an array of Strings and you can't add directly a String to an int. Use this instead :

sum += Integer.parseInt(args[i]); 

Moreover using a for each can make the code easier to read :

for(final String s:args) { 
    sum += Integer.parseInt(s); 
}


sum += args[i];

should be

sum += Integer.parseInt(args[i]);


Command-Line arguments generally accepted as Strings.So you have to first converting it to number and use it like this

sum+=Integer.parseInt(args[i]);


The problem is that you get String from the args arguments when you enter those on the command line. You need to convert them to type Integer.

Use this,

sum += Integer.parseInt(args[i]);


Use sum += Integer.parseInt(args[i]);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜