Hey. I'm having some difficulty in Array lists. I have to find the average of all the numbers in an array list. That's my first task. My second one is to find the mode of all the numbers, meaning the number that shows up the most. And the third one is to find a standard deviation, which I will get to later.

Anyway, right now I'm doing Average.

import java.util.ArrayList;

public class Statistics
{
	public static void main(String args[])
	{
		ArrayList <Integer> intList = new ArrayList <Integer>();
		int avgTemp = 0;
		int count1 = 0;
		
		for (int i = 0; i < intList.size(); i++)
			{
				int b = (int) (Math.random() * 10);
				intList.set(i, b);
			}
	
		for (int i = 0; i < intList.size(); i++)
			{
				int j = intList.get(i);
				avgTemp += j;
				count1++;
			}
	
		System.out.println("The average of all the values in the Array List is " + avgTemp/count1);
	}
}

That's what I have so far. The first for loop makes a random array list, but I think it's wrong. And the second one will store all the integers of the arrayList into avg temp, and then I'll get the average in my output statement. But it doesnt work.

Have you compiled the code? Please mention the errors and the respective line no.s.

The only problem I can see is that your division is an int / int which is always an int. For example, 10 / 4 is 2 (not 2.5). In order to fix that you will need to cast the result to a double or float by doing the following:

System.out.println("The average of all the values in the Array List is " + (double) avgTemp/count1);

Hope I've helped, please let me know if there are still problems.

=java]
public class Statistics
{
   public double getAverage( ArrayList<Integer> source)
   {
      int count=0;
      for( int i=0; i < source.size(); i++ )
      {
         count += source.get( i );
      }
      double result=0;
      result = (double) count / (double) source.size();
      return result;
   }

   public static void main( String [] args )
   {
      System.out.println("Average of 1, 4, 7, 11, 45:");      
      ArrayList<Integer> in = new ArrayList<Integer>();
      in.add( new Integer( 1 ) );
      in.add( new Integer( 4 ) );
      in.add( new Integer( 7 ) );
      in.add( new Integer( 11 ) );
      in.add( new Integer( 45 ) );

      double avg = getAverage( in );
      System.out.println( avg );
   }
}

Something like that above.. I haven't checked it so it may have errors..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.