Java写新建一个student类,包含姓名、年龄、学号三个属性,键盘输入姓名、 年龄、学号来创建三个student对象,创建ArrayList集合 ,把三个对象添加进集合,并遍历集合输出,修改集合元素中年龄最大的对象的姓名为张三;
时间: 2024-03-02 16:49:10 浏览: 26
好的,我来给您写一个 Java 代码实现该功能:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Student {
private String name;
private int age;
private String id;
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
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 getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名、年龄、学号:");
String name = scanner.next();
int age = scanner.nextInt();
String id = scanner.next();
students.add(new Student(name, age, id));
}
System.out.println("添加学生成功,学生信息如下:");
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getId());
}
// 修改年龄最大的学生姓名为张三
int maxAge = 0;
Student maxAgeStudent = null;
for (Student student : students) {
if (student.getAge() > maxAge) {
maxAge = student.getAge();
maxAgeStudent = student;
}
}
maxAgeStudent.setName("张三");
System.out.println("修改年龄最大的学生姓名为张三后,学生信息如下:");
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getId());
}
}
}
```
运行程序后,依次输入三个学生的姓名、年龄、学号,即可创建三个 `Student` 对象,然后把这三个对象添加进 `ArrayList` 集合。接着遍历集合输出所有学生信息,再找到年龄最大的学生对象并修改其姓名为张三,最后再次遍历集合输出所有学生信息,即可看到年龄最大的学生的姓名已经被修改为张三。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)