When I was learning Java, and one of my assignments was to create a program that generated a vertical bar graph of asterisks given user input. Found it so I figured I’d post it -nothing fancy, just something different
/////////////////////////////////////////////////////////////////////////////// import java.io.*; import java.util.Scanner; class LabFour { public static void main (String[] args) { int intBuff, numberOfValues; BarCharter theBarCharter; Scanner inputReader = new Scanner(System.in); System.out.print("How many values will you enter:"); numberOfValues = inputReader.nextInt(); theBarCharter = new BarCharter(numberOfValues); // Begin loop to input all user values for(int i = 0; i < numberOfValues; i++) { // Do, while loop to loop if erroneous input is detected do{ System.out.print("Enter a number between 0 and 10 (inclusive): "); intBuff = inputReader.nextInt(); } while(theBarCharter.addNumber(intBuff) == -1); } // Print the chart theBarCharter.printChart(); } } ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// import java.util.ArrayList; import java.io.*; /* BarCharter - this class is used to create and print vertical asterisk bar graph, given numbers passed in via the addNumber method, using the printChart method. */ public class BarCharter { // ArrayList to hold the user input values private ArrayList userInput; private int numberOfValues, largestValue; // Constructor initializes the object with the passed number of values // from main. BarCharter(int passedValue) { userInput = new ArrayList(); numberOfValues = passedValue; largestValue = 0; } public int addNumber(int passedInt) { int returnVal = 0; // If it meets the criterion for a number if(passedInt >= 0 && passedInt <= 10) { userInput.add(passedInt); if(passedInt > largestValue) { largestValue = passedInt; } } // Else, it doesn't, set return val -1 else { System.out.println("Invalid value. Try again."); returnVal = -1; } // Single entry, single exit, hence the variable return returnVal; } public void printChart() { // Set a loop against the largest value, to print all asterisks for(int i = largestValue; i > 0; i--) { // Begin incrementing through array list for(int k = 0; k < numberOfValues; k++) { // If the current element has a value equal to the outer loop if(userInput.get(k) == i) { // That means that a asterisk is to be printed here System.out.print("*"); // Decrement, so the next time the outer loop // decrements it will be cohesive userInput.set(k, userInput.get(k) - 1); } else { // Else, we know it is a space System.out.print(" "); } } // Drop a line to continue System.out.println(); } } } ///////////////////////////////////////////////////////////////////////////////