EDIT: Ive written code for the average, but i dont know how to make it so that it also uses ints from my args.length rather than the array
I need to write a java program that can calculate: 1. the number of integers read in 2. the average value—which need not be an integer!
NOTE! i dont want to calculate the average from the array but the integers in the args.
Currently i have written this:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
{
for(int i=0; i < nums.length; i++){
result += nums[i];
}
System.out.println(result/count)
}
Can anyone guide me in the right direction? Or give an example that guides me in the write way to shape this code?
Thanks in advance
I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.
If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html
You'll fall into true luv!
This
basically computes
args.length
again, just incorrectly (loop condition should bei<args.length
). Why not just useargs.length
(ornums.length
) directly instead?Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?
Instead of:
you can just
The average is the sum of your args divided by the number of your args.
you can make this code shorter too, i'll let you try and ask if you need help!
This is my first answerso tell me if something wrong!
Just some minor modification to your code will do (with some var renaming for clarity) :
Note that the loop can also be simplified:
Edit: the OP seems to want to use the
args
array. This seems to be a String array, thus updated the answer accordingly.Update:
As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:
This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):
BigDecimal
might be bigger than what fits into adouble
orlong
.