未使用Java重载方法



我有一个活动,需要编写一个重载方法来计算正方形、圆形、梯形和三角形的面积。要求用户输入边的长度、底边、垂直高度和半径的值。使用方法名称AREA((。这是我尝试过的代码,但我总是得到已经定义的错误方法。我试图更改参数的一种数据类型,但没有得到错误,但当我尝试运行程序时,只使用/调用了一个方法。

import java.util.*;
import java.lang.*;
public class Method
{
static double getSides() 
{
double sides;
System.out.print("Input sides here: ");
sides = input.nextDouble();
return sides;
}
static double getRadius() 
{
double radius;
System.out.print("Input radius here: ");
radius = input.nextDouble();
return radius;
}
static double getBase() 
{
double base1;
System.out.print("Input base 1: ");
base1 = input.nextDouble();
return base1;
}
static double getUpperBase() 
{
double base2;
System.out.print("Input base 2: ");
base2 = input.nextDouble();
return base2;
}
static double getHeight() {
double height;
System.out.print("Input height: ");
height = input.nextDouble ();
return height;
}
static double AREA(double sides){
return(sides * sides);
}
static double AREA(double radius){
return (Math.PI * radius * radius);
}
static double AREA(double base1, double height){
return (0.5 * base1 * height);
}
static double AREA(double base1, double base2, double height){
return (0.5 * (base1+base2)* height);
}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
double sides, radius, base1, base2, height;
sides = getSides ();
radius = getRadius ();
base1 = getBase ();
base2 = getUpperBase ();
height = getHeight ();
System.out.printf ("nThe area of the square is: %.4f", AREA(sides));
System.out.printf ("nThe area of the circle is: %.4f", AREA(radius));
System.out.printf ("nThe area of the triangle is: %.4f", AREA(base1,
height));
System.out.printf ("nThe area of the trrapezoid
is: %.4f", AREA(base1,
base2, height));
}
}

您的想法没有问题,但当您试图在java中实现方法重载时,编译器会受到限制。由于您在方法中使用了相似数据类型相同返回类型

static double AREA(double sides){
return(sides * sides);
}
static double AREA(double radius){
return (Math.PI * radius * radius);
}

另外两个重载函数是可以的,因为您已经通过不同数量的参数对它们进行了区分。记住您可以使用

  1. 不同数量的参数
  2. 更改的参数顺序
  3. 方法参数的不同数据类型可以在尝试实现方法重载时区分两种方法

您可以使用的另一种方法是创建一个抽象方法returnTypeArea(数据类型参数1数据类型参数2(并继承。

最新更新