The first homework is to create a new project called "MyOwnCommandLineArguments" as following: 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 09:46:03 浏览: 254
Sure, here's a sample code in Java that meets your requirements:
```java
public class MyOwnCommandLineArguments {
public static void main(String[] args) {
// Check if command line arguments are valid
if (args.length % 2 != 0 || args.length < 6 || args.length > 12) {
System.out.println("Invalid command line arguments. Please enter names and ages of 3 to 6 family members.");
return;
}
// Parse command line arguments and compute average age
int sum = 0;
int count = args.length / 2;
for (int i = 1; i < args.length; i += 2) {
try {
int age = Integer.parseInt(args[i]);
sum += age;
} catch (NumberFormatException e) {
System.out.println("Invalid age for " + args[i - 1] + ". Please enter a valid integer.");
return;
}
}
double average = (double) sum / count;
// Display the average age
System.out.println("The average age of " + count + " family members is " + average);
}
}
```
To run this program, you can open a command prompt or terminal and navigate to the directory where you saved the above code. Then, you can compile and run the code using the following commands:
```
javac MyOwnCommandLineArguments.java
java MyOwnCommandLineArguments Monica 12 Daniel 34 Shelley 23
```
This will output the average age of the three family members provided in the example command line arguments. You can modify the command line arguments to include more family members if needed.
阅读全文