Question:
One of the least Insurance agencies recruited employees for their collection department. Now the HR needs a report as the average age of all the employees working in that department. Write a code to calculate the average age.
Implement a method “calculateAverage(int[] age)” to calculate the average age and return the result to the caller function.
Note:
- Age limit should be minimum of 28 years and maximum of 40 years.
- Minimum of 2 employees is mandatory to calculate average age, if fails, the output should be “Please enter a valid employee count”
- If any of the age is invalid, terminate the process and display “Invalid age encountered!”
Refer the sample given for read and display the output.
Sample Input 1:
Enter total no.of employees:
3
Enter the age for 3 employees:
30
31
32
Sample Output 1:
The average age is 31.00
Sample Input 2:
Enter total no.of employees:
2
Enter the age for 2 employees:
29
36
Sample Output 2:
The average age is 32.50
Sample Input 3:
Enter total no.of employees:
1
Sample Output 3:
Please enter a valid employee count
Code:
Test.java
import java.util.*; import java.text.DecimalFormat; public class Test { double calculateAverage(int[] age) { int len=age.length; double sum=0.0; for(int i=0;i<len;i++) { sum+=age[i]; } double avg=sum/len; return avg; } public static void main (String[] args) { Scanner sc =new Scanner(System.in); Test obj=new Test(); System.out.println("Enter total no.of employees:"); int n=sc.nextInt(); int flag=0; if(n>1) { int[] age=new int[n]; System.out.println("Enter the age for "+n+" employees:"); for(int i=0;i<n;i++) { int temp=sc.nextInt(); if(temp>=28 && temp<=40) { age[i]=temp; } else { System.out.println("Invalid age encountered!"); flag++; break; } } if(flag==0) { DecimalFormat df=new DecimalFormat("####.00"); System.out.println("The average age is "+df.format(obj.calculateAverage(age))); } } else { System.out.println("Please enter a valid employee count"); } } }
Recommended:
- Array square
- Generate number using odd digits
- Alternate Number Difference
- Next Greatest number
- Mark Comparison
- Print the characters in descending order
- Vowels in a fishBowl
- Least offer
- Ascending and descending order
- Mail Domain
- Count repeating words
- Sentence – Convert to upper and lower
- Count consecutive repeating characters
- Zig zag Array
- Pass and Fail Count
- Search a Course
- Average and Grade Calculation
- String – Find and replace the character (first occurrence)
- Sort the first and second half of an array
- Retail Shop
- Palindrome
- Numerology
- InitCap
- Array Compatiblilty
- Sum of the maximum and the minimum element
- String Concatenation
- Find Average Age
- Login