//******************************** // Program Name: histogram.java * // Author: Pat Moss * // Date: Nov 11, 2005 Rev: 01 * // * // Demonstrate a histogram.class * //******************************** import java.util.Scanner; import java.io.*; import javax.swing.*; public class histogram { public static void main (String[] args) throws IOException { System.out.println ("histogram.java by Pat Moss Rev. 01 11-11-2005"); System.out.println (""); // prompt the user to enter the input data text file name // the format is: one integer value per line // with each integer value in the range 1 to 100 JFileChooser chooser = new JFileChooser(); int status = chooser.showOpenDialog (null); if (status != JFileChooser.APPROVE_OPTION) System.out.println ("No File Chosen"); else { File file = chooser.getSelectedFile(); Scanner scan = new Scanner (file); final int VALUEMIN = 1; // minumum valid data integer value final int VALUEMAX = 100; // maximum valid data integer value final int RANGEMIN = 1; // minimum valid range integer value final int RANGEMAX = 10; // maximum valid range integer value int ary1[] = new int[VALUEMAX+1]; int len1 = ary1.length; // get length of the input data array int ary2[] = new int[RANGEMAX+1]; int len2 = ary2.length; // get length of the output data array // Initialize the integer array variables int i=0; for (i=0; i= VALUEMIN) && (inpvalue <= VALUEMAX)) { ary1[inpvalue]++; } } // condense the frequency array ary1 (range 1 to 100) // into the histogram array ary2 (range 1 to 10) for (int k=VALUEMIN; k= RANGEMIN) && (compressedrange <= RANGEMAX)) // if/else #1 { ary2[compressedrange] += datavalue; } else { System.out.println ("*Error: item " + k + " : " + datavalue); } // if/else #1 } // for #1 // Print the results as asterisks per line in a histogram format for (int m = RANGEMIN; m <= RANGEMAX; m++) // for #2 { int mmin = (m - 1) * 10 + 1; int mmax = (m - 1) * 10 + 10; if (mmax < 11) System.out.print (" "); if (mmax < 100) System.out.print (" "); System.out.print (mmin + " - " + mmax + " | "); for (int n=1; n <= ary2[m]; n++) // for #3 { System.out.print ("*"); } // for #3 System.out.println(""); } // for #2 System.out.println (""); System.out.println ("All Done..."); } } }