Write a class MathOperation which accepts integers from command line. Create an array using these parameters. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Write a class MathOperation which accepts integers from command line. Create an array using these parameters.

Write a class MathOperation which accepts integers from command line. Create an array using these parameters. Loop through the array and obtain the sum and average of all the elements. Display the result. Check for various exceptions that may arise like ArithmeticException, NumberFormatException, and so on. For example: The class would be invoked as follows: C:>java MathOperation 1900, 4560, 0, 32500

19th Feb 2017, 8:26 AM
Gagan Kalra
Gagan Kalra - avatar
2 Answers
+ 6
Homework...? Some tips: - You can loop through the argument String[] of the main method to put all containing values to a new int array. - loop through the international array it, e.g. with an enhanced for loop and sum up all elements - after the loop you can calculate the avg by dividing your sum by the number of elements in the array, this is where to use try/catch to prevent an ArithmeticException, which can be thrown, if no arguments are passed to main
7th May 2017, 8:03 AM
Tashi N
Tashi N - avatar
0
package abstractionPackagesExceptionHandling; import java.util.InputMismatchException; public class ExceptionHandling4 { /* *Write a class MathOperation which accepts integers from command line. *Create an array using these parameters. Loop through the array and obtain *the sum and average of all the elements. *Display the result. *Check for various exceptions that may arise like ArithmeticException, NumberFormatException, and so on. *For example: The class would be invoked as follows: *C:>java MathOperation 1900, 4560, 0, 32500 */ public static void main(String[] args) { int[] array = new int[args.length]; try { int sum = 0; for(int i=0; i<args.length; i++) { if(args[i].charAt(args[i].length() - 1) == ',') array[i] = Integer.parseInt(args[i].substring(0, args[i].length() - 1)); else array[i] = Integer.parseInt(args[i]); sum += array[i]; } int avg = sum / args.length; System.out.println("Sum of array is: " + sum + " and average is :" + avg); } catch(ArithmeticException e) { System.out.println("ArithmeticException"); } catch(InputMismatchException e) { System.out.println("InputMismatchException"); } catch(NumberFormatException e) { System.out.println("NumberFormatException"); } } }
16th Jul 2020, 2:56 PM
Manjot Singh
Manjot Singh - avatar