Java Day 14: Scope



Complete the Difference class by writing the following:

A class constructor that takes an array of integers as a parameter and saves it to the elements instance variable.
A computeDifference method that finds the maximum absolute difference between any 2 numbers in N and stores it in the maximumDifference instance variable.



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. class Difference {
  7. private int[] elements;
  8. public int maximumDifference;
  9. Difference(int[] elements) {
  10. this.elements = elements;
  11. }
  12. public void computeDifference() {
  13. int max = 0;
  14. for (int i = 0; i < elements.length; i++) {
  15. for (int j = 0; j < elements.length; j++) {
  16. int abs = Math.abs(elements[i] - elements[j]);
  17. if (abs > max) max = abs;
  18. }
  19. }
  20. maximumDifference = max;
  21. }
  22. // Add your code here
  23. } // End of Difference class
  24. public class Solution {
  25. public static void main(String[] args) {
  26. Scanner sc = new Scanner(System.in);
  27. int n = sc.nextInt();
  28. int[] a = new int[n];
  29. for (int i = 0; i < n; i++) {
  30. a[i] = sc.nextInt();
  31. }
  32. sc.close();
  33. Difference difference = new Difference(a);
  34. difference.computeDifference();
  35. System.out.print(difference.maximumDifference);
  36. }
  37. }