import java.io.IOException; import java.io.PrintStream; import java.util.Iterator; /** * Small class to generate a crude histogram plot. * * @author geoffreytowell * */ public class Histogrammer { /** * The histogram marker */ private static final String MARK = "X"; /** * Write a histogram to System.out * @param hdata the data to be plotted */ public void fauxHistogram(int[] hdata) { fauxHistogram(hdata, System.out); } /** * Write a histogram to the named file * @param hdata the data to be plotted * @param filename the file to be written to */ public void fauxHistogram(int[] hdata, String filename) { try { PrintStream fileWriter = new PrintStream("c:/temp/samplefile3.txt"); fauxHistogram(hdata, fileWriter); fileWriter.close(); } catch (IOException ioe) { System.err.println(ioe.toString()); } } /** * Write a histogram to the PrintWriter * @param hdata the data to be plotted * @param ps the PrintWriter to which to write */ public void fauxHistogram(int[] hdata, PrintStream ps) { // first get the highest and lowest non-zero data points int ff=-1; int ll=-1; for (int i=0; i0 && ff<0) ff=i; if (hdata[i]>0) ll=i; } if (ff<0) ps.println("No data to Histogram"); // Now plot the data, showing only from lowest to highest for (int i=ff; i<=ll; i++) { // use String.format to make things look nice ps.print(String.format("%2d (%4d)", i, hdata[i])); // ternary operator limits printing to 70 marks for (int j=0; j<(hdata[i]<=70?hdata[i]:70); j++) ps.print(MARK); ps.println(); } } public static void main(String[] args) { DataProvider dg = new DataProvider(50, 500); dg.setRange(50); Iterator itr = dg.iterator(); int[] data = new int[50]; while(itr.hasNext()) { int tmp = itr.next(); if (tmp>0) data[tmp-1]++; } new Histogrammer().fauxHistogram(data); } }