public class ArrayPrinting
1: import java.util.Scanner;
2: import java.util.Arrays;
4: /**
5: * A class with methods that do what they're supposed to!
6: */
8: public class ArrayPrinting {
9: /** The only Scanner for the keyboard */
10: public static final Scanner KBD = new Scanner(System.in);
12: public static void main(String[] args) {
13: // introduce yourself
14: System.out.print("\n\n"
15: + "Printing and Sorting Arrays\n"
16: + "---------------------------\n\n");
18: // create a couple of arrays
19: int[] arr1 = makeIntArr(90, 1000);
20: int[] arr2 = makeIntArr(90, 50);
22: // show the first array before and after sorting
23: System.out.println("int[] arr1 (original):");
24: printArr(arr1);
25: System.out.println("int[] arr1 (sorted):");
26: Arrays.sort(arr1);
27: printArr(arr1);
28: pause();
30: // show the second array before and after sorting
31: System.out.println("int[] arr2 (original):");
32: printArr(arr2);
33: System.out.println("int[] arr2 (sorted):");
34: Arrays.sort(arr2);
35: printArr(arr2);
36: pause();
37: }
39: /**
40: * Create an array of randomly chosen positive integers.
41: * THAT'S ITS JOB. THAT'S WHAT IT DOES!
42: *
43: * @param size the number of elements in the array
44: * @param max the largest number allowed in the array
45: * @return an array of length <tt>size</tt>
46: * with elements in the range 1 to <tt>max</tt>.
47: */
48: public static int[] makeIntArr(int size, int max) {
49: int[] result = new int[size];
50: for (int i = 0; i < size; i++)
51: result[i] = (int)(max * Math.random() + 1);
52: return result;
53: }
55: /**
56: * Print an array in a nice table, 10 elements per line.
57: * THAT'S ITS JOB. THAT'S WHAT IT DOES!
58: *
59: * @param arr the array to print
60: */
61: public static void printArr(int[] arr) {
62: for (int i = 0; i < arr.length; i++) {
63: if (i % 10 == 0) {
64: System.out.println();
65: }
66: System.out.printf("%7d", arr[i]);
67: }
68: System.out.print("\n\n");
69: }
71: /**
72: * Wait for the user to press the enter key.
73: * THAT'S ITS JOB. THAT'S WHAT IT DOES!
74: */
75: public static void pause() {
76: System.out.print("Press Enter...");
77: KBD.nextLine();
78: System.out.println();
79: }
80: }