/** * Generate an array of 10000 random numbers from 0 to 4. * Report the percentage of each number (0,1,2,3 and 4) * Use methods to do each task. */ import java.text.*; import javax.swing.*; public class RandomArray { /** * Creates an array of integers(of size 10000). Fills the array * with integers randomly chosen between 0 and 4. Computes and prints the number * of occurences of each integer as a percentage. */ public void processRandomArray() { // Define an array of integers of size 10000 int[] array = new int[10000]; // Fill the array with random numbers between 0 and 4 // Use the method fillRandomly this.fillRandomly(array); // Report the percentage of each number // Use the method report this.computeAndPrintReport(array); } /** * Fills an array with random integers between 0 and 4 * @param a the array to fill */ private void fillRandomly(int[] a) { // Fill the array with random numbers between 0 and 4 for (int i = 0; i < a.length; i ++) { a[i] = (int) (Math.random() * 5); } } /** * Computes and prints the percentage of occurences of 0,1,2,3 and 4 in an array * @param a the array to scan. */ private void computeAndPrintReport(int[] a) { // one way int n0 = 0, n1 = 0, n2 = 0, n3 = 0, n4 = 0; for (int i = 0; i < a.length; i ++) { switch (a[i]) { case 0: n0 ++; break; case 1: n1 ++; break; case 2: n2 ++; break; case 3: n3 ++; break; case 4: n4 ++; break; } } String s = ""; s += "Number of 0's = " + (100.0 * n0 / a.length) + "%\n"; s += "Number of 1's = " + (100.0 * n1 / a.length) + "%\n"; s += "Number of 2's = " + (100.0 * n2 / a.length) + "%\n"; s += "Number of 3's = " + (100.0 * n3 / a.length) + "%\n"; s += "Number of 4's = " + (100.0 * n4 / a.length) + "%\n"; JOptionPane.showMessageDialog(null, s, "Results", JOptionPane.INFORMATION_MESSAGE); // other way int[] count = new int[5]; for (int i = 0; i < a.length; i ++) { count[a[i]] ++; } StringBuffer sb = new StringBuffer(); NumberFormat nf = NumberFormat.getPercentInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); for (int i = 0; i < count.length; i ++) { sb.append("Number of " + i + "'s = " + nf.format((double) count[i] / a.length) + "\n"); } // Print s as well to compare with sb JOptionPane.showMessageDialog(null, s + "\n\n" + sb.toString(), "Results", JOptionPane.INFORMATION_MESSAGE); } }