0

运行我的程序时,出现以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

at CylinderTest.main(Cylinder.java:42)

我确信有一个简单的解决方案,但我是一个没有经验的程序员,对我来说它似乎应该工作。

程序说明:编写一个名为 CylinderTest.java 的类,并声明一个由三个 Cylinder 对象组成的数组,以调用您在 Cylinder 类中声明的方法。确保从 main() 调用所有类方法。让 main() 显示 volume() 返回的值,并通过手动计算(纸/铅笔)验证返回的值。提示用户输入数组中每个 Cylinder 对象的半径和高度值。

public class Cylinder 
{
  private double radius;
  private double height;
  public Cylinder(double radius, double height)
  {
      this.radius = radius;
      this.height = height;
  }
  public double getRadius()
  {
      return radius;
  }
  public double getHeight()
  {
      return height;
  }
  public double volume()
  {
      return radius*radius*height*3.1416;
  }


}

public class CylinderTest
{

public static void main(String[] args) 
{

    Cylinder[] myCylinder = new Cylinder[3];
    myCylinder [0] = new Cylinder (2,7);
    myCylinder [1] = new Cylinder (9,3);
    myCylinder [2] = new Cylinder (12,4);
    for (Cylinder c: myCylinder)
    {
        System.out.println("*******");
        System.out.println("Radius: " + c.getRadius());
        System.out.println("Height: " + c.getHeight());
        System.out.println("Volume: " + c.volume());
        System.out.println("*******");
    }
}
}   
4

3 回答 3

1

线程“main”java.lang.Error 中的异常:未解决的编译问题:

在 CylinderTest.main(Cylinder.java:42)

由于文件第 42 行存在错误,您的类Cylinder无法编译Cylinder.java

于 2012-11-13T23:52:10.330 回答
1

这是因为您在一个文件中有两个单独的公共类。将 CylinderTest 拆分为自己的文件。一般来说,有一个分隔测试类的目录结构是有用的:

src
   main
      java
   test
      java

您还应该为 Cylinder (say) org.me 创建一个包名

在这种情况下,两个类都应该有

package org.me;

在顶部。

您应该使用 IDE(例如 Eclipse 或 Netbeans),这会在您尝试运行它之前告诉您存在编译错误。通常运行有错误的程序是一个糟糕的主意,而且通常很难判断发生的位置和情况。但是 Eclipse 通常会提供一个堆栈跟踪,该堆栈跟踪将链接到有问题的行。

于 2012-11-14T00:07:17.260 回答
0

Woot4Moo 已经解释了异常的直接原因。基本上,您不能运行使用具有编译错误的类的程序。在尝试运行程序之前修复所有编译错误:

  • 如果您在 Eclipse 中访问该文件,编译错误应标记为红色。

  • 如果工作区中存在编译错误,您可以将 Eclipse 配置为不允许您运行代码。

由于我们看不到实际的编译错误,我无法确定这一点。但是,我怀疑根本问题是您在一个文件中有两个顶级public类(称为“Cylinder.java”)。你不能在 Java 中做到这一点。非嵌套public类必须位于单独的源文件中。(您可以使用“包私有”类来避免这样做,但这是不好的做法。)

解决方法是将 Cylinder 和 CylinderTest 类放在单独的源文件中。

(理想情况下,您还应该添加包声明,但我猜您的讲师尚未向您解释这些内容。)

于 2012-11-14T00:12:46.757 回答