Calculate average in java

后端 未结 10 2139
悲哀的现实
悲哀的现实 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: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

提交回复
热议问题