I am trying to make a histogram with inputting a value and rounding it. The rounded value should print out the number of asterisks.
I did the following code and inputted a value but, the output is coming out as nothing.
public class Histogram
{
public static void main(String args[])
{
histogram obj = new histogram();
obj.histogram(13.5);
}
}
class histogram
{
public void histogram(double num)
{
int roundNum = (int)(num);
if (roundNum == 14)
{
System.out.println("**************" num);
}
if (roundNum == 3)
{
System.out.println("***" num);
}
if (roundNum == 16)
{
System.out.println("****************" num);
}
if (roundNum == 0)
{
System.out.println("" num);
}
if (roundNum == 1)
{
System.out.println("*" num);
}
}
}
CodePudding user response:
In Java, typecasting to primitive type int from primitive type double can be thought of as simply removing the decimal part.
For example;
System.out.println((int) 13.1); // prints 13
System.out.println((int) 13.5); // prints 13
System.out.println((int) 13.9); // prints 13
So, when you call obj.histogram(13.5); with the function parameter num being 13.5, the operation int roundNum = (int)(num); is the same as int roundNum = (int)(13.5);, and assigns 13 to the roundNum variable.
Since no if statements handle this case (roundNum being 13), no output is generated.
On another note, hardcoding a lot of if statements for checking the same variable over and over again can usually lead to unnecessarily complex, inefficient and hard-to-read code. Can you think of a better way to print "*" characters for the histogram, by using the roundNum variable? (Hint: try experimenting with for loops)
CodePudding user response:
Change your int roundNum = (int)(num); to int rounded = Math.round((float)num); it should give you the desired output.
