My assignment asks me to take a data set in the form of different integers, and run them through a method that will print the appropriate number of characters to create a horizontal bar graph.
The graph needs to use a string made of Block Elements (█, ▏, ▌). The blocks are base 8, so inputting 8 as in integer should print █ and 16 should print ██.
I figured out a way to print the right number of blocks for inputs that are evenly divisible by 8, but I'm not sure how I can work with the remainders or decimal values from uneven division e.g., if (9 / 8) = 1.125, how can I use the 0.125?
This is what I have so far. It prints the appropriate number of characters for multiples of 8.
public static String getHorizontal(int value) {
String bar = "";
double realMath = (double) value / 8; // (1/8) = (0.125) (8/8) = 1
int rmConversion;
while (realMath % 1 == 0) {
rmConversion = (int) realMath;
for (int i = 0; i < rmConversion; i++) {
bar += "█";
}
return bar;
}
// TODO: replace this with code that actually generates the bar graph!
return bar;
}
How can I run a similar loop but with a remainder or decimal point value?
Here is one way. Note that all the calculcations in this answers are done in integer arithmetic. No floating point is used.
%operator to calculate the remainder, which will give the size of a partial block.Arrays.fillcall with your loop.Test:
The uneven height between the full block and the partial blocks seem to be a result of the font Stack Overflow is using. I do not see that difference in the test result anywhere else, such as my IDE, email, or a text editor.
An alternative to using
partBlockarray is to take advantage of the fact that the partial blocks are consecutive characters in Unicode:Of course, the space character doesn't fit in that pattern, so a check has to be done for that.