import java.text.DecimalFormat;import java.text.NumberFormat;import java.util.Random;/** * An example application for displaying a simple text-based chart. * * @author pchapman */public class GraphExample{ private static final int MAX_BAR_LENGTH = 20; public static void main(String[] args) { // Holds the value of the maximum data point int maxValue = Integer.MIN_VALUE; // Holds the data to graph int[] values = new int[20]; // First, calculate 10 random values Random random = new Random(); for (int i = 0; i < values.length; i++) { values[i] = random.nextInt(); if (values[i] < 1) { // We only want positive integers. Go through the loop again i--; } else { if (values[i] > maxValue) { // We have a new highest value maxValue = values[i]; } } } // Now that we have the data, we can graph it. float percentOfMax; int astrisks; NumberFormat format = new DecimalFormat("00"); for (int i = 0; i < values.length; i++) { // Find out what percentage of the max value this value represents // Must cast values or else we will get a rounded result percentOfMax = (float)values[i] / (float)maxValue; astrisks = (int)(MAX_BAR_LENGTH * percentOfMax); // Output the bar title System.out.print(format.format(i)); System.out.print(": "); for (int j = 0; j < astrisks; j++) { System.out.print("*"); } System.out.print(" ("); System.out.print(String.valueOf(values[i])); System.out.println(")"); } }}