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 in java
时间: 2023-12-03 09:46:05 浏览: 71
Here's an example Java program that receives the names and ages of family members as command line arguments:
```java
public class FamilyAges {
public static void main(String[] args) {
// Check if there are at least 3 arguments
if (args.length < 6 || args.length % 2 != 0) {
System.out.println("Usage: java FamilyAges <name1> <age1> <name2> <age2> ...");
return;
}
// Parse the arguments and store them in arrays
String[] names = new String[args.length / 2];
int[] ages = new int[args.length / 2];
for (int i = 0; i < args.length; i += 2) {
names[i / 2] = args[i];
ages[i / 2] = Integer.parseInt(args[i + 1]);
}
// Print the names and ages of the family members
System.out.println("Family members:");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + " - " + ages[i] + " years old");
}
}
}
```
To run this program, you would type something like the following in the command prompt or terminal:
```
java FamilyAges Monica 12 Daniel 34 Shelley 23
```
This would output:
```
Family members:
Monica - 12 years old
Daniel - 34 years old
Shelley - 23 years old
```
阅读全文