// This class contains several small examples of array and String manipulation. // Each is written as a method. import java.util.*; public class ArraySample2 { public static void main(String[] args) { // this is an example of a good practice problem for arrays mystery(); int[] data = {-8, 274, -54, 782, 92, 42, -384, 17}; System.out.println("data = " + Arrays.toString(data)); applyAbs(data); System.out.println("after applyAbs, data = " + Arrays.toString(data)); String s = "hello there"; System.out.println("s = " + s); String s2 = reverse(s); System.out.println("s2 = " + s2); int num = 229231007; countDigits(num); } // practice problem: what is in the array after the loop? 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; } } } // This method replaces any negative integers in the given array with the // absolute value of the integer. public static void applyAbs(int[] list) { for (int i = 0; i < list.length; i++) { list[i] = Math.abs(list[i]); } } // This method returns a String that is twice as long as the original // with each character from the original appearing twice in the result public static String reverse(String text) { // String processing is similar to array processing: // list.length => s.length() // list[i] => s.charAt(i) String result = ""; for (int i = 0; i < text.length(); i++) { result = text.charAt(i) + result; } return result; } // This method counts how many of each digit there are in the current // number and prints the result public static void countDigits(int number) { int[] count = new int[10]; System.out.print("Digit counts for " + number + " = "); while (number > 0) { int digit = number % 10; number = number / 10; count[digit]++; } System.out.println(Arrays.toString(count)); } }