繁体   English   中英

Java 未使用重载方法

[英]Java overload method not used

我有这个活动,我需要编写一个重载方法来计算正方形、圆形、梯形和三角形的面积。 要求用户输入边长、底边、垂直高度和半径的值。 使用方法名称 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 中实现方法重载时存在编译器限制。由于您使用的 arguments 具有相似的数据类型相同的返回类型,因此这两个函数会产生问题:

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

其他两个重载函数没问题,因为您通过不同数量的参数来区分它们。 记住你可以使用

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

您可以使用的另一种方法是创建一个抽象方法returnType Area( datatype parameter1 , datatype parameter2 ) 并继承。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM