Input/Output: Graphics: Simple Bar Graph

Screen Shot 2014-12-07 at 12.13.44 PM


Looking at the printf method
A printf format reference page (cheat sheet)

// This class shows how to initialize an array 
// How to use the printf output formatting method
public class InitPrintfArray 
{
   public static void main( String[] args )
   {
      // initializing the array when it is created
      int[] arrayA = { 87,56,78,99,102 };

      System.out.printf( "%s%7s\n", "Index", "Value" ); // column headings
   
      // output each array element's value 
      for ( int i = 0; i < arrayA.length; i++ )
         System.out.printf( "%5d%5d\n", i, arrayA[ i ] );
   } // end main
} // end class InitPrintfArray

A "simplified" version of a bar chart by using the elements of an array as counters

// Bar graph printing program.

public class BarGraph 
{
   public static void main( String[] args )
   {
      int[] arrayA = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };

      System.out.println( "Grade distribution:" ); 

      // for each array element, output a bar of the chart
      for ( int i = 0; i < arrayA.length; i++ ) 
      {
         // output bar label ( "00-09: ", ..., "90-99: ", "100: " )
         if ( i == 10 )
            System.out.printf( "%5d: ", 100 ); 
         else
            System.out.printf( "%02d-%02d: ", 
               i * 10, i * 10 + 9  ); 
 
         // print bar of asterisks
         for ( int stars = 0; stars < arrayA[ i ]; stars++ )
            System.out.print( "*" );

         System.out.println(); // start a new line of output
      } // end outer for
   } // end main
} // end class BarGraph

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Claswork/Homework:
Tracing 101: Trace the i, arrayA[i], and the output as the inner and outer loops traverse arrayA.