Can I do it this way?
Here is the bit of code I am questioning:
double area = roundResult(cyl.getSurfaceArea());
double volume = roundResult(cyl.getVolume());
Can I pass a method as an argument? (or am I passing it as a parameter)
Here is the whole program. Does everything look okay?
Any help is appreciated. Thanks in advance.
import java.util.Scanner; //importing the Scanner class for use
public class TestCylinder
public static void main(Stringargs)
Scanner K = new Scanner(System.in); //creating a new instance of the Scanner class called K
System.out.print("Enter Cylinder Radius ans Width ie 4 5 "); //Prompt for user to input radius and width
double radius = K.nextDouble(); //assigning the first number the user inputs to the variable radius
double height = K.nextDouble(); //assigning the second number the user inputs to the variable height
Cylinder cyl = new Cylinder(radius,height); //creating a new instance of the Cylinder class called cyl which accepts the parameters radius and height
[B]double area = roundResult(cyl.getSurfaceArea())[/B]; //creating a variable whos value is the result of getSurfaceArea passed as an argument to the roundResult method
[B]double volume = roundResult(cyl.getVolume());[/B] //creating a variable whos value is the result of getVolume passed as an argument to the roundResult method
System.out.println("Surface Area = " + area); //prints the value of the variable area
System.out.println("Volume = " + volume); //prints the value of the variable volume
public static double roundResult(double num)
num = num * 100; //num (the value of area/value passed as arguments) = num * 100; moving the decimal two places to the right
num = Math.round(num); //rounding the value of num
num = num / 100; //moving the decimal two places to the left
return num; //returning the rounded result
Does your program works. So far this looks OK.
Yes, everything works fine.
I just didn't know if I could pass a method as an argument like I did. Also, I wasn't sure if my comments accurately described what was happening in the code.
I'm sure there is an easier way of rounding, but that is what I have thus far. It seems to work okay.
You're not passing a method into another method, you're calling the method and passing its result which is fine to do.
What was your intention with roundResult()?
If you want to round the number with two decimals there are different ways.
Yes, my intention was to round the answer down to two decimal places. We haven't learned any other way of doing it at this point, so I did it that way. I am assuming the logic is correct.
It is OK as I said, later you could use DecimalFormat