[英]Error passing array to a function. It is not able to compile
My array should be passed to a function, but my program has an error and does not compile.我的数组应该传递给一个函数,但我的程序有错误并且无法编译。 What am I doing wrong?我究竟做错了什么?
- I am getting an error on line 13: "a1e.averData(scores,MAX_SIZE);"我在第 13 行收到错误消息:“a1e.averData(scores,MAX_SIZE);”
- The error states,"non-static variable scores cannot be referenced from a static context. Assign Return Value to New Variable"错误状态,“不能从静态上下文中引用非静态变量分数。将返回值分配给新变量”
- I also tried assigning the return value to a new variable.我还尝试将返回值分配给一个新变量。 It looked like this: "float averData = a1e.averData(scores,MAX_SIZE);"它看起来像这样:“float averData = a1e.averData(scores,MAX_SIZE);”
- The error changed to this: "non-static variable scores cannot be referenced from a static context. non-static variable MAX_SIZE cannot be referenced from a static context"错误更改为:“不能从静态上下文引用非静态变量分数。不能从静态上下文引用非静态变量 MAX_SIZE”
- I have tried moving it from the main to other spots in the program, but it just doesn't seem to want to work for me, and I am unsure of how to fix it.我曾尝试将它从程序中的主要位置移动到其他位置,但它似乎并不适合我,而且我不确定如何修复它。
Here is my code:这是我的代码:
package array1example;
public class Array1example
{
int i, sum;
float avg;
int scores[];
int MAX_SIZE = 0;
/**
*
* @param args
*/
public static void main(String[] args)
{
/* An example of an array being passed to a function
This program stores integers in an array
and computes their average*/
Array1example a1e = new Array1example();
}
public Array1example()
{
this.scores = new int[]{5, 5, 12, 17, 11};
a1e.averData(scores,MAX_SIZE);
}
private float averData(int[] scores1, int MAX_SIZE1)
{
int size = 0;
for(i=0, sum=0; i<size; i++)
{
System.out.println("Score " + " = " + scores1[i] );
sum += (scores1[i]);
}
avg = sum / i;
System.out.println("Average score: " + avg );
return avg;
}
}
You can't use a1e.averData(scores,MAX_SIZE);
你不能使用a1e.averData(scores,MAX_SIZE);
in your constructor, instead change it into averData(scores,MAX_SIZE);
在您的构造函数中,改为将其更改为averData(scores,MAX_SIZE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.