I am writing a class which is supposed to populate an array with random integers. The size of the array is given via user input via the scanner class. You are then supposed to include methods for obtaining the average, minimum, and maximum values, as well as a toString method for displaying the random integers. I have written out the class but cannot get the methods to work in my Driver program. I use array.getMax() and it returns a cannot be applied to given types throw. And my String only ever returns the array address. Can someone please show me where I went wrong?
Class:
import java.util.*;
public class RandomArray {
public int size;
private static Random gen = new Random();
public RandomArray()
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
size = scan.nextInt();
int[] array = new int[size];
for (int i = 0; i < array.length; i++)
array[i] = gen.nextInt(50) + 1;
}
public int getMax(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
if (array[i] > max) {
max = array[i];
}
return max;
}
public int getMin(int[] array)
{
int min = 52;
for (int i = 0; i < array.length; i++)
if (array[i] < min) {
min = array[i];
}
return min;
}
public double getAvg(int[] array)
{
double total = (double) size;
double avg, sumOf;
int sum = 0;
for (int i : array)
sum += i;
sumOf = (double) sum;
avg = sumOf / total;
return avg;
}
public String toString(int[] array)
{
String result = "";
for (int i = 0; i < array.length; i++)
result = result + array[i];
return result;
}
}
Here is the driver program (I also do not know how to make the average display after I have called it):
import java.util.*;
public class RandomArrayDriver {
public static void main(String[] args)
{
int value;
RandomArray one = new RandomArray();
one.getAvg();
one.getMax();
one.getMin();
System.out.print("The contents are: " + one.toString());
}
}
Based on the code you posted, it shouldn't run in this state. When I ran it I got different exceptions than you reported, but nonetheless, here's a few pointers to get it running:
Your constructor for RandomArray
is initializing array
as a local variable and as soon as it is done, that reference is lost. Most likely what you want is to make the array
an instance variable instead. Then, your other class methods can access that array when they are doing their calculations.
In your RandomArrayDriver
, you are making calls to your class methods on the one
instance without passing parameters, but your definitions for those methods in RandomArray
specify one int[]
argument. If you refactor your code based on the point made above, you should be able to remove these and your driver will run correctly.
Hopefully that is enough to get you started. These changes should get the program running at least and other fixes after that should be obvious formatting of the output (hint: toString
will output things a little weird in it's current state).