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
This
for (int i = 0; i<args.length -1; ++i)
count++;
basically computes args.length
again, just incorrectly (loop condition should be i<args.length
). Why not just use args.length
(or nums.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?
It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.
Arrays.stream(<arr>)
. Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s))
which will convert stream of Strings into stream of doubles.Stream.collect(supplier, accumulator, combiner)
to calculate average if you want to control incremental calculation yourselves. Here is some good example.Collectors.averagingDouble()
which directly calculates and returns average. some examples here.Instead of:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
you can just
int count = args.length;
The average is the sum of your args divided by the number of your args.
int res = 0;
int count = args.lenght;
for (int a : args)
{
res += a;
}
res /= count;
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!
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums
array at all