因此Java函数返回零

时间:2014-04-29 18:14:03

标签: java

首先对标题感到抱歉我无法想象我应该如何标题。分配的提示让我们用三个不同的类(两个带有构造函数和一个测试类的类)计算金字塔和棱镜的体积和表面积,并且标题表示我一直为零。

这是棱镜类:

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());
    }
}

2 个答案:

答案 0 :(得分:4)

您的构造函数声明了局部变量并忽略了实例变量。实例变量未初始化,因此Java会将它们初始化为默认值0

E.g。变化

double l = intL;

l = intL;

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

答案 1 :(得分:1)

hiding的班级字段为variable shadows;

public Prism(double intL, double intW, double intH)
{
  // double l = intL;
  // double w = intW;
  // double h = intH;
  this.l = intL;
  this.w = intW;
  this.h = intH;
}

和金字塔中的同样问题 -

public Pyramid(double intB, double intH)
{
   // double b = intB;
   // double h = intH;
   this.b = intB;
   this.h = intH;
}