|
发表于 2023-5-6 19:18:10
|
显示全部楼层
本楼为最佳答案
这是一个简化版的Java信息管理系统。我们将使用命令行界面(CLI)进行交互。为了让代码简单易懂,我们使用ArrayList存储数据,避免使用数据库。系统将有四个字段:ID(整数)、姓名(字符串)、年龄(整数)和邮箱(字符串)。
首先创建一个Person类来存储用户信息:
public class Person {
private int id;
private String name;
private int age;
private String email;
public Person(int id, String name, int age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}
然后创建一个InformationSystem类,包含添加、修改、删除和显示功能:
import java.util.ArrayList;
public class InformationSystem {
private ArrayList<Person> persons;
public InformationSystem() {
persons = new ArrayList<>();
}
public void addPerson(int id, String name, int age, String email) {
persons.add(new Person(id, name, age, email));
}
public void modifyPerson(int id, String name, int age, String email) {
for (Person person : persons) {
if (person.getId() == id) {
person.setName(name);
person.setAge(age);
person.setEmail(email);
break;
}
}
}
public void deletePerson(int id) {
persons.removeIf(person -> person.getId() == id);
}
public void displayPersons() {
for (Person person : persons) {
System.out.println(person);
}
}
}
接下来,创建主类(Main)来运行程序,接受用户输入并执行相应操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
InformationSystem informationSystem = new InformationSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1. 添加 2. 修改 3. 删除 4. 显示 5. 退出");
int choice = scanner.nextInt();
if (choice == 5) {
break;
}
int id;
String name;
int age;
String email;
switch (choice) {
case 1:
System.out.println("请输入ID:");
id = scanner.nextInt();
System.out.println("请输入姓名:");
name = scanner.next();
System.out.println("请输入年龄:");
age = scanner.nextInt();
System.out.println("请输入邮箱:");
email = scanner.next();
informationSystem.addPerson(id, name, age, email);
break;
case 2:
System.out.println("请输入要修改的ID:");
id = scanner.nextInt();
System.out.println("请输入新的姓名:");
name = scanner.next();
System.out.println("请输入新的年龄:");
age = scanner.nextInt();
System.out.println("请输入新的邮箱:");
email = scanner.next();
informationSystem.modifyPerson(id, name, age, email);
break;
case 3:
System.out.println("请输入要删除的ID:");
id = scanner.nextInt();
informationSystem.deletePerson(id);
break;
case 4:
informationSystem.displayPersons();
break;
default:
System.out.println("无效的操作,请重新选择。");
break;
}
}
scanner.close();
}
}
这个简化版的信息管理系统应该足够让新手理解。程序将运行在命令行界面,并根据用户输入执行相应的操作。请尝试运行并测试代码。如有疑问,请随时提问。 |
|