1、定义一个person类,属性有姓名、年龄、籍贯属性,创建3个person对象,切割字符串”小明 23 河北;小红 24 山东;小辉 22 北京“得到属性分别赋值给上面3个对象,并将这3个对象存入数组中,打印输出数组中年龄最大的person对象。(10分钟)
时间: 2024-10-27 20:07:22 浏览: 17
首先,让我们定义一个Person类,包含姓名、年龄和籍贯这三个属性:
```java
public class Person {
private String name;
private int age;
private String hometown;
// 构造函数
public Person(String name, int age, String hometown) {
this.name = name;
this.age = age;
this.hometown = hometown;
}
// 获取和设置属性的方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getHometown() { return hometown; }
public void setHometown(String hometown) { this.hometown = hometown; }
@Override
public String toString() {
return "Name: " + name + ", Age: " + age + ", Hometown: " + hometown;
}
}
```
接下来,我们将创建三个Person对象,从给定的字符串中提取信息并赋值:
```java
String str = "小明 23 河北;小红 24 山东;小辉 22 北京";
String[] parts = str.split(";"); // 切割字符串
Person[] people = new Person[3];
for (int i = 0; i < parts.length; i += 3) {
String name = parts[i];
int age = Integer.parseInt(parts[i+1]);
String hometown = parts[i+2];
people[i / 3] = new Person(name, age, hometown);
}
// 找到年龄最大的person
int maxAgeIndex = 0;
for (int i = 1; i < people.length; i++) {
if (people[i].getAge() > people[maxAgeIndex].getAge()) {
maxAgeIndex = i;
}
}
System.out.println("The person with the maximum age is:");
System.out.println(people[maxAgeIndex]);
```
运行这段代码,你会看到年龄最大的那个人的信息被打印出来。
阅读全文