Java编程调试测验

Java编程调试测验,java,Java,这个测验分为两部分。首先是 public class FixDebugBox { private int width; private int length; private int height; private double Volume; public void FixDebugbox() { length = 1; width = 1; height = 1; } public FixDebugBox(int

这个测验分为两部分。首先是

public class FixDebugBox {
   private int width;
   private int length;
   private int height;
     private double Volume;

   public void FixDebugbox() {
     length = 1;
     width = 1;
     height = 1;
   }
   public FixDebugBox(int width, int length, int height) {
      width = width;
      length = length;
      height = height;
   }
   public void showData() {
     System.out.println("Width: "  + width + "  Length: " +
      length + "  Height: " + height);
   }
   public double getVolume() { 
     double vol = length * width * height;
         return Volume;
   }
}
上面的代码是测验的一半,上面的代码编写正确,但第二部分我不能

public class FixDebugFour3
// This class uses a FixDebugBox class to instantiate two Box objects
{
   public static void main(String args[])
   {
      int width = 12;
      int length = 10;
      int height = 8;

      FixDebugBox box1 = new FixDebugBox(width, length, height);
      FixDebugBox box2 = new FixDebugBox(width, length, height);
      System.out.println("The dimensions of the first box are");
      box1.showData();
      System.out.println("The volume of the first box is");
      showVolume(box1);
      System.out.println("The dimensions of the first box are");
      box2.showData();
      System.out.println("The volume of the second box is");
      showVolume(box2);
   }
   public void showVolume() {
      double vol = FixDebugBox.getVolume();
      System.out.println(vol);
   }

}
我一直在使用double vol=FixDebugBox.getVolume()时出错;错误:无法从静态上下文引用非静态方法getVolume()

FixDebugBox.getVolume();
getVolume
是非静态方法,不能用类名调用它,它是一个公共方法,需要对象来调用它

   public void showVolume(FixDebugBox box) {
      double vol = box.getVolume();
      System.out.println(vol);
   }

现在把奖品给我。:D

我想你已经回答了自己的问题。您需要保留对
FixDebugBox
实例的引用才能调用其非静态方法。

正如错误消息所述,您不能从作为主要方法的静态上下文调用非静态方法。虽然您可以将
showVolume()
转换为静态方法,并将
FixDebugBox
实例作为参数,但查看
FixDebugBox
对象如何已经有了
getVolume()
方法,只需为每个实例调用它:

System.out.println(box1.getVolume());
...
System.out.println(box2.getVolume());
另外,不要将
变量的名称更改为
。如果移动,则应使用camelCase.

public void showVolume() {
  double vol = FixDebugBox.getVolume();
  System.out.println(vol);
}
类FixDebugBox
并删除
class FixDebugBox
中的
getVolume()
方法,并将
showVolume()
方法更改为:

public void showVolume() {
    double vol = length * width * height;
    Volume = vol;
    System.out.println(Volume);
}

这将修复您的程序。另外,
boxVolume
Volume
更好,因为变量不应该用大写字母书写。

如果这是一个测验,那么奖励是什么?如果这是一个测验,问题是什么?提交作业的时间线是什么?你正在做
showVolume(box1)
但是
showVolume()
不接受方框(提示:应该接受)。