Bar Chart

The problem

Write a program that asks the user to enter today’s sales for five stores. The program should display a bar chart comparing each store’s sales. Create each bar in the chart by displaying a row of asterisks. Each asterisk should represent $100 of sales.

Here is example of the program’s output:

Enter today’s sales for stores 1: 1000
Enter today’s sales for stores 2: 1200
Enter today’s sales for stores 3: 1800
Enter today’s sales for stores 4: 800
Enter today’s sales for stores 5: 1900

Sales Bar Chart:

Store 1: **********
Store 2: ************
Store 3: ******************
Store 4: ********
Store 5: *******************

Breaking it down

static int CHAR_PER_SALE = 100;

public static void main(String[] args) {

    double sales;
    List<Double> storeSales = new ArrayList<>();

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    do {
        // ask user for input
        System.out.print("Enter today's sales for store 1: ");
        sales = keyboard.nextDouble();

        // add input to collection
        storeSales.add(new Double(sales));

    } while (sales != -1);

    // close scanner
    keyboard.close();

    // Display the bar chart heading.
    System.out.println("\nSALES BAR CHART");

    // Display chart bars
    for (Double sale : storeSales) {
        System.out.println("Store:" + getBar(sale));
    }
}

/**
 * Method should return the number of chars to make up the bar in the chart.
 * 
 * @param sales
 * @return
 */
static String getBar(double sales) {

    int numberOfChars = (int) (sales / CHAR_PER_SALE);

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < numberOfChars; i++) {
        buffer.append("*");
    }

    return buffer.toString();
}

Output

Enter today's sales for store 1: 1000
Enter today's sales for store 1: 1100
Enter today's sales for store 1: 1200
Enter today's sales for store 1: 1300
Enter today's sales for store 1: -1

SALES BAR CHART
Store:**********
Store:***********
Store:************
Store:*************
Store:

Unit tests

@Test
public void chart_length() {
    
    String chars = BarChart.getBar(1000);
    
    assertTrue(chars.length() == 10);
}

Level Up

  • Modify program to allow user to enter a character to make up the bar chart.
  • Fix the input and output for store numbers
  • Add message to user about quitting the program -1
  • Fix the output to exclude the quit parameter