Receive the ages of the all your family members (between 3 to 6 members) as command line arguments in the format as following (name then age) Monica 12 Daniel 34 Shelley 23 Compute and display the average of the ages that were entered.in java
时间: 2023-12-03 19:46:01 浏览: 90
使用java计算年龄
5星 · 资源好评率100%
Here's a Java program that receives the ages of family members as command line arguments and calculates the average age:
```java
public class FamilyAgeAverage {
public static void main(String[] args) {
// Check if there are at least 3 command line arguments
if (args.length < 6 || args.length % 2 != 0) {
System.out.println("Usage: java FamilyAgeAverage name1 age1 name2 age2 ...");
return;
}
// Parse the ages and calculate the average
int sum = 0;
for (int i = 1; i < args.length; i += 2) {
sum += Integer.parseInt(args[i]);
}
double avg = (double)sum / (args.length / 2);
// Print the average age
System.out.printf("The average age of %d family members is %.2f\n", args.length / 2, avg);
}
}
```
To run this program, open a command prompt or terminal, navigate to the directory containing the `FamilyAgeAverage.java` file, and compile it with the command:
```
javac FamilyAgeAverage.java
```
Then run the program with the command:
```
java FamilyAgeAverage Monica 12 Daniel 34 Shelley 23
```
You can replace these names and ages with your own family members' names and ages. The output should be:
```
The average age of 3 family members is 23.00
```
阅读全文