使用数组,保存用户的年龄信息,并分别定义方法,
获取用户的最高年龄,添加用户年龄,并为用户的年龄排序等功能。
public class UserTest {
static Scanner input = new Scanner(System.in);
static User[] users = new User[10];
public static void main(String[] args) {
init();
Function();
}
public static void init() {
// 初始化用户
User user1 = new User();
user1.setName("张三");
user1.setAge(30);
users[0] = user1;
User user2 = new User();
user2.setName("李四");
user2.setAge(10);
users[1] = user2;
User user3 = new User();
user3.setName("王五");
user3.setAge(20);
users[2] = user3;
}
// 功能操作
private static void Function() {
int choose = 0;
do {
System.out.println("***用户管理***");
System.out.println("1:显示用户列表(按年龄排布)");
System.out.println("2:添加用户年龄");
System.out.println("3:获取最大年龄用户");
System.out.println("0:退出");
System.out.println("请输入编号:");
choose = input.nextInt();
switch (choose) {
case 1:
showUser();
break;
case 2:
System.out.println("请输入姓名:");
String name = input.next();
System.out.println("请输入年龄:");
int age = input.nextInt();
addUser(name, age);
break;
case 3:
findMaxUser();
break;
case 0:
break;
default:
break;
}
} while (choose != 0);
}
// 显示用户列表(按年龄从大到小排布)
public static void showUser() {
for (int i = 0; i < users.length - 1; i++) {
for (int j = 0; j < users.length - 1 - i; j++) {
if (users[j + 1] == null)
break;
if (users[j].getAge() < users[j + 1].getAge()) {
User user = users[j];
users[j] = users[j + 1];
users[j + 1] = user;
}
}
}
System.out.println("排名\t用户姓名\t用户年龄");
for (int i = 0; i < users.length; i++) {
if (users[i] == null)
break;
System.out.println(i + 1 + "\t" + users[i].getName() + "\t" + users[i].getAge());
}
}
// 添加用户年龄
public static void addUser(String name, int age) {
int index = -1;
for (int i = 0; i < users.length; i++) {
if (users[i] == null) {
index = i;
break;
}
}
if (index != -1) {
User user = new User();
user.setName(name);
user.setAge(age);
users[index] = user;
return;
}
User[] newUsers = new User[users.length * 2];
for (int i = 0; i < newUsers.length; i++) {
newUsers[i] = users[i];
}
users = newUsers;
for (int i = 0; i < users.length; i++) {
if (users[i] == null) {
User user = new User();
user.setName(name);
user.setAge(age);
users[index] = user;
return;
}
}
}
// 获取最大年龄用户
public static void findMaxUser() {
for (int i = 0; i < users.length - 1; i++) {
for (int j = 0; j < users.length - 1 - i; j++) {
if (users[j + 1] == null)
break;
if (users[j].getAge() < users[j + 1].getAge()) {
User user = users[j];
users[j] = users[j + 1];
users[j + 1] = user;
}
}
}
System.out.println("年龄最大的用户是" + users[0].getName() + ",年龄是" + users[0].getAge() + "岁");
}
}
public class User {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}