fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Main {
  6.  
  7. public static void main (String args[]){
  8. int numbers[]= {1,5,-9,12,-3,89, 18,23,4,-6};
  9.  
  10. try {
  11. // Find minimum (lowest) value in array using loop
  12. System.out.println("Minimum Value = " + getMinValue(numbers));
  13.  
  14. // Find maximum (largest) value in array using loop
  15. System.out.println("Maximum Value = " + getMaxValue(numbers));
  16.  
  17. // Find average of all elements
  18. System.out.println("Average Value = " + getAvgValue(numbers));
  19.  
  20. // Sort the numbers and print the sorted array
  21. Arrays.sort(numbers);
  22. System.out.print("Sorted Array: ");
  23. for(int num : numbers){
  24. System.out.print(num + " ");
  25. }
  26. System.out.println();
  27.  
  28. // Challenge: Find median
  29. System.out.println("Median Value = " + getMedianValue(numbers));
  30.  
  31. } catch (ArithmeticException e) {
  32. System.out.println("Error: Division by zero.");
  33. System.out.println("Error: Array index out of bounds.");
  34. } catch (Exception e) {
  35. System.out.println("Error: " + e.getMessage());
  36. }
  37. }
  38.  
  39. // Find maximum (largest) value in array using loop
  40. public static int getMaxValue(int[] numbers){
  41. int maxValue = numbers[0];
  42. for(int i=1; i<numbers.length; i++){
  43. if(numbers[i] > maxValue){
  44. maxValue = numbers[i];
  45. }
  46. }
  47. return maxValue;
  48. }
  49.  
  50. // Find minimum (lowest) value in array using loop
  51. public static int getMinValue(int[] numbers){
  52. int minValue = numbers[0];
  53. for(int i=1; i<numbers.length; i++){
  54. if(numbers[i] < minValue){
  55. minValue = numbers[i];
  56. }
  57. }
  58. return minValue;
  59. }
  60.  
  61. // Find the average of an array of integers
  62. public static double getAvgValue(int[] numbers){
  63. double sum = 0;
  64. for(int num : numbers){
  65. sum += num;
  66. }
  67. if(numbers.length == 0){
  68. throw new ArithmeticException("Cannot compute average of empty array.");
  69. }
  70. return sum / numbers.length;
  71. }
  72.  
  73. // Challenge: Find the median of the array
  74. public static double getMedianValue(int[] numbers){
  75. int len = numbers.length;
  76. if(len == 0){
  77. throw new ArithmeticException("Cannot compute median of empty array.");
  78. }
  79. // The array should be sorted before calling this function.
  80. if(len % 2 == 1){
  81. return numbers[len/2];
  82. } else {
  83. return (numbers[len/2 - 1] + numbers[len/2]) / 2.0;
  84. }
  85. }
  86. }
Success #stdin #stdout 0.16s 57696KB
stdin
Standard input is empty
stdout
Minimum Value = -9
Maximum Value = 89
Average Value = 13.4
Sorted Array: -9 -6 -3 1 4 5 12 18 23 89 
Median Value = 4.5