kila
kila

Reputation: 1

How to calculate average of array input correctly?

when I put any amount of numbers it give me wrong average I dont know why I tried many ways but still average doesnt work correctly what I did wrong to get wrong result? any suggestion..

import java.util.Scanner;
public class Assignment_Help2 {
    public static void main(String[] args){
        Scanner keyboard = new Scanner (System.in);

        String[] department = new String[5];
        int[] employeesno = new int[5];
        String [] address = new String[5];

        int index;
        index = 0;
        int totalentered = 0;
        String temp;

        // One loop to enter all information
        //INPUT LOOP
        for (index = 0; index < 5; index++)
        {
                System.out.print("Enter a department  or stop ..: ");
                department[index] = keyboard.nextLine();
                if (department[index].equals("stop"))
                {
                    break;

                }
                System.out.print("employees_no: ");
                temp = keyboard.nextLine();
                // convert string to a number & then store it as integer in the array
                employeesno[index] = Integer.valueOf(temp);

                System.out.print("Enter address: ");
                address[index] = keyboard.nextLine();   
                totalentered++;

        } //END OF FOR LOOP

        System.out.println("==================================");   

        System.out.println(String.format("%-20s", "department")+
                String.format("%-18s", "no_employees")+ 
                String.format("%-20s", "Address"));



        // Another separate loop to display the information stored in arrays
        //OUTPUT LOOP   
        for (index = 0; index < totalentered; index++)
        {

            System.out.println(String.format("%-20s", department[index]) + 
                     String.format("%-18d", employeesno[index])+ 
                     String.format("%-20s", address[index]));    

        } 

        int sum1=0;
        double average;
        for(int l=0; l <employeesno.length  ; l++) 
         {
           sum1 += employeesno[l];
         } average= sum1/employeesno.length;
         System.out.println("aver= "+average);
         keyboard.close();      
    }
}

Upvotes: 0

Views: 46

Answers (1)

Kevin Anderson
Kevin Anderson

Reputation: 4592

sum1 is an int; employeesno.length is an int, so sum1 / employeesno.length is computed by integer division. Write

average = ((double) sum1) / employeesno.length`;

instead to carry out the division in doubles

Upvotes: 1

Related Questions