我没有得到答案(立方体积)
它不断返回0.0
作为答案,我无法弄清楚我做错了什么。为什么volume()
方法实际上不会乘以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
答案 0 :(得分:6)
永远不会调用执行计算的方法volume
。最好从方法本身返回结果以避免这种类型的逻辑错误
public double getVolume() {
return cubeSide * cubeSide * cubeSide;
}
答案 1 :(得分:5)
volumeAnswer尚未设置为任何内容。
首先调用cube1.volume()