java - For loop troubling for printing multiple values -
so question is: write program reads sequence of input values , displays bar chart of values using asterisks. may assume values positive. first figure out maximum value. value’s bar should drawn 40 asterisks. shorter bars should use proportionally fewer asterisks. eg.
*********************** ********* **************************************** **** *******************
this code below:
int count = 0; //finds largest value int largestvalue = numbersarray[0]; (int = 1; < numbersarray.length; i++) { if (numbersarray[i] > largestvalue) { largestvalue = numbersarray[i]; count++; } } //prints number of asterisks final int max = 40; string asterisks = "****************************************"; (int = 0; < count + 2; i++) { system.out.print(numbersarray[i]); if (numbersarray[i] == largestvalue) { system.out.print(asterisks); } //if (numbersarray[i] != largestvalue) { else { (int j = 0; j < (40 * numbersarray[i] / largestvalue); j++) { system.out.print("*"); } } system.out.println(); }
this code doesn't seem run properly. if enter values in order: 5 8 6 4 7, print stars 5 , 8, , not rest. prints stars values till largest number.
i can't find what's wrong code. appreciated!
thanks reading <3
first of all, don't need count
variable - nothing helpful , reason limit (you increment everytime find larger element increment once since there's nothing larger 8).
what should doing finding largest value, did, , running on entire array , displaying each element proportional value, did (but without special case actual largest value - atrocious).
also, should note division of 2 integers result in integer
, not want, you'll have cast 1 of them float
or double
.
//finds largest value int largestvalue = numbersarray[0]; (int = 1; < numbersarray.length; i++) { if (numbersarray[i] > largestvalue) { largestvalue = numbersarray[i]; } } //prints number of asterisks final int max = 40; (int = 0; < numbersarray.length; i++) { int portion = (int)(max * (numbersarray[i] / (float)largestvalue)); (int j = 0; j < portion; j++) { system.out.print("*"); } system.out.println(); }
so you'll find largest value 8.
then 5, you'll 5/8 0.625 , times max
(40) 25, you'll print 25 *
.
then 8 - 8/8 = 1.0 * max = 40
you'll print whole 40 *
.
for 6 - 6/8 = 0.75 * max = 30
you'll print 30 *
, on.
note if want fine-tune it, use math.round
instead of casting portion
int (which truncates floating point).
Comments
Post a Comment