So to start off I am self-learning Java and ran into a wall with printing out a bar chart using asterisks. I've got the algorithm down on how to print positive values and I think I've gotten the gist of what I need to do to handle negative values. What I can't do it convert that idea into code. This is what I'm working with:
public class BarChart
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random gen = new Random();
// Read for input of array legnth
System.out.print("Enter Array Length: ");
int n = gen.nextInt(6) + 10;
System.out.println(n);
int[] values = new int[n];
int randNum;
for(int i = 0; i < n; i++)
{
// Get random number to add to the array
randNum = gen.nextInt(20) + 1;
values[i] = randNum;
}
print(values);
System.out.println();
values[3] = -2;
// Print each element as asterisks
for(int i = 0; i < values.length; i++)
{
if(values[i] < 0)
{
printAsterisk(values[i] * -1);
System.out.printf("%20d:\n", values[i]);
}
else
{
System.out.printf("%20d:", values[i]);
printAsterisk(values[i]);
System.out.println();
}
}
}
// Methods
/**
* Prints an array
* @param array array
*/
public static void print(int[] array)
{
for(int i = 0; i < array.length; i++)
{
if(i > 0)
{
System.out.print(" | ");
}
System.out.print(array[i]);
}
System.out.println();
}
public static void printAsterisk(int val)
{
for(int i = 0; i < val; i++)
{
System.out.print("*");
}
}
}
This gets me close to what I want but what I get is this:
Enter Array Length: 14
13 | 13 | 4 | 5 | 11 | 1 | 3 | 13 | 3 | 4 | 19 | 4 | 10 | 10
13:*************
13:*************
4:****
** -2:
11:***********
1:*
3:***
13:*************
3:***
4:****
19:*******************
4:****
10:**********
10:**********
Note: The array length and elements are all randomly determines. In my given example above, I explicitly change one of the elements to a negative value just for testing purposes using values[3] = -2.
The asterisks where there are negative values should look like something like this:
**[-2]
[5 ]*****
***[-3]
[9 ]*********
I also had trouble using %20d to print what I wanted in the above example. But that's not the main concern here. As in I'm fine with it printing something like:
5: *****
** -2:
6: ******
**** -4:
What I was thinking is that I need to indent from the left a certain amount and then printing the asterisks necessary and then printing the number of asterisks withing brackets. So my question is how would I change my code to produce the output I want.