gpt4 book ai didi

java - 过载错误?

转载 作者:行者123 更新时间:2023-12-01 10:22:09 25 4
gpt4 key购买 nike

下面是我当前的代码。我必须创建一个数组系统,通过对 Java 类使用重载来返回一些随机数的平均值。然而,当我编译时,BlueJ 告诉我有一个“方法 myAverage(int []) 已在类重载中定义”错误,我不知道该怎么做才能修复它。

谢谢!

/**
* Write a description of class overload here.
*
* @author (your name)
* @version (a version number or a date)
*/

import java.util.Scanner;
import java.lang.Math;

public class overload
{
private static int myAverage (int [ ] arrayone)
{
int sum = 0;

for(int i=0; i < arrayone.length ; i++)
{
sum = sum + arrayone[i];
}
double average = sum / arrayone.length;

return average;
}

private static int myAverage (int [ ] arraytwo)
{
int sum = 0;

for(int i=0; i < arraytwo.length ; i++)
{
sum = sum + arraytwo[i];
}
double average = sum / arraytwo.length;

return average;
}

public static void main (String [ ] args)
{
Scanner scan = new Scanner(System.in);

System.out.println("Enter any number below.");
System.out.print("Enter the integer here: ");
int x = scan.nextInt();

int [] arrayone = new int [x];

for (int i = 0; i < arrayone.length; i++)
{
arrayone[ i ] = (int)(Math.random( ) * 100) + 1;
}


myAverage(arrayone);

System.out.println("\n\nThe average of the first array is : " + average);

System.out.println("\n\nEnter any number below.");
System.out.print("Enter the integer here: ");
int y = scan.nextInt();

int [] arraytwo = new int [y];

for (int i = 0; i < arraytwo.length; i++)
{
arraytwo[ i ] = (double)(Math.random( ) * 100) + 1;
}

myAverage(arraytwo);
}
}

最佳答案

"method myAverage(int []) is already defined in class overload" error

您有两个具有相同签名的方法

private static int myAverage (int [ ] arrayone)

删除任何一个即可。并将 return 类型更改为 double,因为您返回的是 double 类型的 average

private static double myAverage (int [ ] arrayone)
<小时/>

I do not understand what you are saying

就您而言,这不是方法重载。方法重载意味着

1.方法返回类型必须不同。

例如:

private static double myAverage (int [ ] arrayone){ 
^
}

private static int myAverage (int [ ] arrayone){
^
}

2.参数数量必须不同。

例如:

private static int myAverage (int [ ] arrayone){
^
}

private static int myAverage (int [ ] arrayone, int [ ] arraytwo){
^ ^
}

3.参数类型必须不同。

例如:

private static int myAverage (double [ ] arrayone){
^
}

private static int myAverage (int [ ] arrayone){
^
}

其中任何一个都必须是真实的。

关于java - 过载错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com