// Program showing some additional array practice problems. // Each problem is a method, and main contains sample calls // to those methods to demonstrate their behavior. import java.util.*; public class ArrayPractice { public static void main(String[] args) { int a = 5; int b = 7; System.out.println(a + " " + b); swap(a, b); System.out.println(a + " " + b); System.out.println(); int[] nums = {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(nums)); modify(nums); System.out.println(Arrays.toString(nums)); System.out.println(); double[] vals = {-10.2, 3.5, 9.7, 12.5, 1.3, -0.4, 11.1, 10.0}; System.out.println(Arrays.toString(vals)); cap(vals, 0, 10); System.out.println(Arrays.toString(vals)); reverse(vals); System.out.println(Arrays.toString(vals)); System.out.println(); } // We saw that this is correct code for swapping two int values, but it // only swaps the local copies of these values and has no effect on any // variables that are used in calling the method. public static void swap(int x, int y) { System.out.println("Before swap: " + x + " " + y); int temp = x; x = y; y = temp; System.out.println("After swap: " + x + " " + y); } // We saw that this method was able to change the array contents because // of reference semantics. public static void modify(int[] list) { list[0] = -724; list[1] = -425; } // a method to limit all values in an array to within a given range public static void cap(double[] nums, double min, double max) { for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { nums[i] = max; } else if (nums[i] < min) { nums[i] = min; } // nums[i] = Math.min(nums[i], max); // nums[i] = Math.max(nums[i], min); } } // this method reverses the sequence of values in an array public static void reverse(double[] list) { for (int i = 0; i < list.length / 2; i++) { double first = list[i]; double last = list[(list.length - 1) - i]; list[i] = last; list[(list.length - 1) - i] = first; } } // an example of an array mystery problem--there will a problem like this // on the final. public static void mystery() { int[] a = {1, 7, 5, 6, 4, 14, 11}; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } } System.out.println("mystery array = " + Arrays.toString(a)); } }