Passing an array through a method
Hey guys, first post. I've searched the forums and I've found a few other posts that were similar to my question but they weren't enough for me to figure out my problem. So, I'm trying to pass an array though this method, getAverage. When I run my StatsDemo class it is supposed to use this getAverage method with a random array to find the average. I have included my getAverage method and my StatsDemo class. Thanks in advance, let me know if I can change anything.
Code:
public class Stats
{
public static int getAverage(int[] array)
{
int average = 0, total = 0;
for(int i = 0; i < array.length; i++)
{
total = total + array[i];
average = total/array.length;
}
return average;
}
public class StatsDemo
{
public static void main(String[] args)
{
Random random = new Random(2621);
int [] array = new int[20];
for (int i = 0; i < array.length; i++)
array[i] = random.nextInt(64 - 19) + 1;
System.out.println("The max of the array is:" + getAverage(array)); //I get a "cannot find symbol" error.
}
}
Re: Passing an array through a method
Hello and welcome!
Please tell us, what is your question? What is the problem with the code above? The more you can tell us, usually the better we can help. Also consider editing your post above and adding [code] [/code] tags around your code.
Re: Passing an array through a method
Ah, I see that your question is buried in your unformatted code, hiding in fact.
The problem is that you're trying to call a static method without specifying the class that owns the method. For instance when you want to use the standard out's PrintStream's println method, you don't do
Instead you have to specify the name of the class (and variable) for this method:
Code:
System.out.println("hello");
Same for your code -- you must call your getAverage method off of the Stats class. Also, as an aside, you shouldn't calculate the average *inside* of the for loop. Wait until all numbers have been added to total, and then after the for loop ends, calculate the average then. It might not make a big difference, but it is a more elegant way to do this.
Re: Passing an array through a method
Alright thanks, I formatted it better now. To make my question more clear, how can I use the method of getAverage in the StatsDemo class? And when I call the getAverage method in the StatsDemo class, it needs to use the 20 random integer array that is created there. I hope that makes it easier for you to help. Would I have to write Stats.getAverage() to use it?
Re: Passing an array through a method
I already gave you the answer. Please read my second post above.
Re: Passing an array through a method
Alright I re-read and figured it out. Thanks for the quick and friendly help! Have a good night