Calculate average in java

后端 未结 10 2135
悲哀的现实
悲哀的现实 2020-12-11 07:49

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

相关标签:
10条回答
  • 2020-12-11 08:14

    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?

    0 讨论(0)
  • 2020-12-11 08:17

    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.

    • In your case, you want to convert args which is String[] into double or int. You can do this using 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.
    • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
    • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
    0 讨论(0)
  • 2020-12-11 08:21

    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!

    0 讨论(0)
  • 2020-12-11 08:23

    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

    0 讨论(0)
提交回复
热议问题