Lab 9 - Stats

2 posts / 0 new
Last post
carneye5
Lab 9 - Stats

 

Hi,
I have the first part of this program compiling ok for the stats exercise. It allows me to put in 10 integers but then when it comes to getting max, min etc i get  an error
                            Exception in thread "main" java.lang.NullPointerException
                            at Stats.getMin(Stats.java:38)
                            at Stats.main(Stats.java:65)
Any ideas?
Thanks, 
Eoin
 
 
import java.util.*;
 
public class Stats
{
//get numbers
private int[] numbers;
{
 
int[]numbers=new int[10];
 
Scanner sc = new Scanner(System.in);
 
for(int i = 0; i<numbers.length; i++)
{
System.out.println("Enter integer "+ (i+1)+ " ");
numbers[i] = sc.nextInt();
}
 
}
 
//get the maximum
public int getMax()
{
int max=numbers[0];
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>max)
{
max = numbers[i];
}
}
return max;
}
 
//gets the minimum
public int getMin()
{
int min = numbers[0];
for (int i=1; i<numbers.length; i++)
{
if(numbers[i]<min)
{
min = numbers[i];
}
}
return min;
}
 
//gets the average
public double getAverage()
{
int total=0;
for(int i=0; i<10; i++)
{
total = total+numbers[i];
}
double avg = (double)(total/10);
return avg;
}
 
public static void main(String [] args)
{
Stats sort = new Stats();
 
int lowest = sort.getMin();
int highest = sort.getMax();
 
System.out.println("Maximum is " + highest);
System.out.println("Minimum is " + lowest);
 
double average = sort.getAverage();
 
System.out.println("Average is " + average);
}
}
dardiso2
Re: Lab 9 - Stats

Hi Eoin,

The NullPointerException could be because you need to have a constructor to initialise the object first...

public Stats()

{

fill the array in here

}

Give it a go.

Orla

Login to post comments