首先,对标题感到抱歉,我想不出该如何命名的。分配提示使我们用三个不同的类(两个带有构造函数的类和一个测试类)来计算金字塔和棱柱的体积和表面积,作为标题,我一直保持为零。

这是棱镜类:

public class Prism
{
double l;
double w;
double h;
public Prism(double intL, double intW, double intH)
 {
     double l = intL;
     double w = intW;
     double h = intH;
 }
 public double getPrismVolume()
 {
     return l*w*h;
 }
 public double getPrismSurfaceArea()
 {
     return 2*((l*w)+(h*l)+(h*w));
 }
}


这是我的金字塔课:

public class Pyramid
{
    double b;
    double h;
    public Pyramid(double intB, double intH)
    {
       double b = intB;
       double h = intH;
    }
    public double getPyramidVolume()
    {
       return (1.0/3.0)*Math.pow(b,2)*h;
    }
    public double getPyramidSurfaceArea()
    {
        return Math.pow(b,2)+(2*b*h);
    }
}


这是我的测试课:

import java.util.*;
public class GeometryTest
{
 public static void main(String[] args)
    {
    Scanner myScanner = new Scanner(System.in);
    System.out.print("Enter the length of the prism: ");
    String answer1 = myScanner.nextLine();
    double length = Double.parseDouble(answer1);
    System.out.print("Enter the width of the prism: ");
    String answer2 = myScanner.nextLine();
    double width = Double.parseDouble(answer2);
    System.out.print("Enter the height of the prism: ");
    String answer3 = myScanner.nextLine();
    double height = Double.parseDouble(answer3);
    System.out.print("Enter the pyramid's base: ");
    String answer4 = myScanner.nextLine();
    double base = Double.parseDouble(answer4);
    System.out.print("Enter the pyramid's height: ");
    String answer5 = myScanner.nextLine();
    double pyramidHeight = Double.parseDouble(answer5);
    Pyramid aPyramid = new Pyramid(base,pyramidHeight);
    Prism aPrism = new Prism(length,width,height);
    System.out.println("The prism's volume is: " + aPrism.getPrismVolume());
    System.out.println("The prism's surface area is: " + aPrism.getPrismSurfaceArea());
    System.out.println("The pyramid's volume is: " + aPyramid.getPyramidVolume());
    System.out.println("The pyramid's surface area is: " +  aPyramid.getPyramidSurfaceArea());
    }
}

最佳答案

您的构造函数正在声明局部变量,而忽略实例变量。实例变量保持未初始化状态,因此Java将其初始化为默认值0

例如。更改

double l = intL;




l = intL;


因此l将解析为实例变量名称。

10-07 13:40
查看更多