Java having problem to find an average

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • raj000
    New Member
    • Mar 2015
    • 1

    Java having problem to find an average

    When I run the following program to find an average it shows: "Exception in thread "main" java.lang.Array IndexOutOfBound sException: 0
    at average.Average .main(Average.j ava:32)"

    Can anyone help me plz.




    Code:
    package average;
    import java.util.Scanner;
    
    
    /**
     *
     * @author MdTazimulIslam
     */
    public class Average {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
        double avg;
            int sum=0;
            Scanner input=new Scanner(System.in);
        int i=0;
        
        int n;
        System.out.println("Array length: ");
        n=input.nextInt();
        int []A=new int[i];
        System.out.println("The numbers: ");
        for(i=0;i<n;i++)
        A[i]=input.nextInt();
        for(i=0;i<n;i++)
        {
            sum=sum+A[i];
        }
        avg=sum/n;
                System.out.println("The average is: "+avg);
    
        
        
        }
        
    }
    Last edited by Rabbit; Mar 25 '15, 01:55 AM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Please use code tags when posting code or formatted data.

    You're creating the array based on I when the array size is stored in n.

    Comment

    Working...