简体   繁体   中英

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**

    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); 
}

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

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM