I am failing to get an answer (volume of a cube)
It keeps returning 0.0
as an answer and I could not figure out what I am doing wrong. Why isn't the volume()
method actually multiplying the cubeSide
?
import java.util.Scanner;
class Cube{
private double cubeSide;
private double volumeAnswer;
//default const
public Cube(){
cubeSide = 0;
}
//argument constructor
public Cube(double inp){
cubeSide = inp;
}
//method for volume
public void volume(){
volumeAnswer = cubeSide * cubeSide * cubeSide;
}
//returning value
public double returnIt(){
return volumeAnswer;
}
}//end of class cube
public class myCubeClass{
public static void main(String[] args){
/*
Cube class
- Two constructors (one default and the other with length argument)
- A method called "Volume"
- A Method called getVolume
*/
//create new cube object
Cube cube1 = new Cube(3.23);
System.out.println("Ans: " + cube1.returnIt());
}//end of main
}//end of class
The method volume
that performs the calculation is never called. Better to return the result from the method itself to avoid this type of logical error
public double getVolume() {
return cubeSide * cubeSide * cubeSide;
}
volumeAnswer hasn't been set to anything yet.
Call cube1.volume() first
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.