我遇到了一个问题,我们需要使用方法重载来计算球体、圆柱体和圆锥体的体积。以下是我的代码,绝对没问题:
import java.util.*;
class Vol_Sph_Cyl_Con
{
void calc_volume(double sp_rd)
{
double volume=(4*3.14*(Math.pow(sp_rd,3)))/3;
System.out.println("Volume of the sphere is "+volume+" cc");
}
void calc_volume(double cyl_rd, double cyl_he)
{
double volume=3.14*(Math.pow(cyl_rd,2))*cyl_he;
System.out.println("Volume of the cylinder is "+volume+" cc");
}
void calc_volume(double con_rd,double con_he,double pie)
{
double volume=(pie*(Math.pow(con_rd,2))*con_he)/2;
System.out.println("Volume of the cone is "+volume+" cc");
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Vol_Sph_Cyl_Con ob=new Vol_Sph_Cyl_Con();
double sp_rad=0.0;
do
{
System.out.println("Enter radius of sphere to calculate the volume (in centimetres)");
sp_rad=sc.nextDouble();
if (sp_rad<=0)
{
System.out.println("Error!");
}
}while (sp_rad<=0);
ob.calc_volume(sp_rad);
double cyl_rad=0.0, cyl_hei=0.0;
do
{
System.out.println("Enter the radius and the height of cylinder respectively to calculate volume (in centimetres)");
cyl_rad=sc.nextDouble();
cyl_hei=sc.nextDouble();
if (cyl_rad<=0 || cyl_hei<=0)
{
System.out.println("Error!");
}
}while (cyl_rad<=0 || cyl_hei<=0);
ob.calc_volume(cyl_rad,cyl_hei);
double con_rad=0.0, con_hei=0.0, pi=3.14;
do
{
System.out.println("Enter radius and height of cone respectively to calculate volume (in centimetres)");
con_rad=sc.nextDouble();
con_hei=sc.nextDouble();
if (con_rad<=0 || con_hei<=0)
{
System.out.println("Error!");
}
}while (con_rad<=0 || con_hei<=0);
ob.calc_volume(con_rad,con_hei,pi);
}
}
这个程序绝对没问题,但问题是,因为这是一个学校项目,我不能在计算 cone 值的方法中传递参数“pie”,因为我们不允许显式传递一些不是必需的。但如果我不这样做,参数的数量就会一致。有没有办法解决这个问题,还是只是问题的问题?
最佳答案
目前,您的参数是要计算其体积的几何体的定义值。如果您有两个或更多几何体共享相同的定义值类型,您将丢失,因为您无法仅根据类型来区分它们,因为它们是相等的。正如tobias_k所指出的那样.
要解决此问题,您可以为代码中需要的每个几何体添加一个表示。这些可以用作您的体积计算方法的单一参数。
因此,对于您的示例,您需要:一个球体、一个圆柱体和一个锥体类。
public class Sphere {
}
public class Cylinder {
}
public class Cone {
}
由于这是一项作业,我们应该让您思考如何设计这些类。您的重载方法如下所示:
void calc_volume(Sphere sphere) {}
void calc_volume(Cylinder cylinder) {}
void calc_volume(Cone cone) {}
如您所见,您可以使用此设计处理的几何对象数量没有进一步限制。
关于java - Java 方法重载期间重合的参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37728710/