编制一个学生籍贯信息记录簿,每个学生信息包括:学号、姓名、籍贯。具体功能如下:
(1)创建学生信息并以磁盘文件保存;
(2)读取磁盘文件并显示输出所有学生的籍贯信息;
(3)按学号或姓名查询成绩;
(4)按籍贯查询并输出该籍贯的所有学生;
(5)能添加、删除和修改学生的籍贯信息(可选项);
引用new bing作答:
以下是一个 Java 实现的学生籍贯信息记录簿,实现了上述功能:
import java.io.*;
import java.util.*;
class Student implements Serializable {
private int id;
private String name;
private String address;
public Student(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "ID: " + id + "\tName: " + name + "\tAddress: " + address;
}
}
public class StudentRecord {
private static ArrayList<Student> students = new ArrayList<Student>();
private static Scanner scanner = new Scanner(System.in);
private static void save() {
try {
FileOutputStream fileOut = new FileOutputStream("students.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(students);
out.close();
fileOut.close();
System.out.println("Student records saved to file students.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void load() {
try {
FileInputStream fileIn = new FileInputStream("students.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
students = (ArrayList<Student>) in.readObject();
in.close();
fileIn.close();
System.out.println("Student records loaded from file students.ser");
} catch (IOException e) {
System.out.println("No saved student records found");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void addStudent() {
System.out.println("Enter student ID:");
int id = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter student name:");
String name = scanner.nextLine();
System.out.println("Enter student address:");
String address = scanner.nextLine();
students.add(new Student(id, name, address));
save();
}
private static void deleteStudent() {
System.out.println("Enter student ID:");
int id = scanner.nextInt();
scanner.nextLine();
for (Student student : students) {
if (student.getId() == id) {
students.remove(student);
System.out.println("Student with ID " + id + " deleted");
save();
return;
}
}
System.out.println("No student with ID " + id + " found");
}
private static void modifyStudent() {
System.out.println("Enter student ID:");
int id = scanner.nextInt();
scanner.nextLine();
for (Student student : students) {
if (student.getId() == id) {
System.out.println("Enter new student address:");
String address = scanner.nextLine();
student.setAddress(address);
System.out.println("Student with ID " + id + " modified");
save();
return;
}
}
System.out.println("No student with ID " + id + " found");
}
private static void displayAllStudents() {
for (Student student : students) {
System.out.println(student);
}
}
private static void displayStudentsByLocation() {
System.out.println("Enter location:");
String location = scanner.nextLine();
boolean found = false;
for (Student student : students) {
if (student.getAddress().equalsIgnoreCase(location)) {
System.out.println(student);
found = true;
}
}
if (!found) {
System.out.println("No students found in " + location);
}
}
private static void searchStudent() {
System.out.println("Enter student ID or name:");
String input = scanner.nextLine();
boolean found = false;
for (Student student : students) {
if (student.getId() == Integer.parseInt(input) || student.getName().equalsIgnoreCase(input)) {
System.out.println(student);
found = true;
}
}
if (!found) {
System.out.println("No student found with ID or name " + input);
}
}
public static void main(String[] args) {
load();
while (true) {
System.out.println("\nWhat would you like to do?");
System.out.println("1. Add a student");
System.out.println("2. Delete a student");
System.out.println("3. Modify a student");
System.out.println("4. Display all students");
System.out.println("5. Display students by location");
System.out.println("6. Search for a student");
System.out.println("0. Exit");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
addStudent();
break;
case 2:
deleteStudent();
break;
case 3:
modifyStudent();
break;
case 4:
displayAllStudents();
break;
case 5:
displayStudentsByLocation();
break;
case 6:
searchStudent();
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
}
}
该程序使用了一个 Student
类来表示每个学生,包含学号、姓名和籍贯。使用 ArrayList
来存储所有学生的信息,并使用序列化将其保存到磁盘文件中。
在主方法中,使用一个 while
循环来处理用户的不同操作选择。用户可以选择添加、删除、修改学生信息,或者查询所有学生信息或者按照籍贯查询学生信息。还可以搜索学生信息,通过输入学号或姓名来查找相应的学生。
该程序实现了一个基本的学生籍贯信息记录簿,可以根据需要进行扩展和改进。
基于ChatGPT的回答:
import java.io.*;
import java.util.*;
public class Stu implements Serializable{
private int id;
private String name;
private String hometown;
public Stu(int id, String name, String hometown){
this.id = id;
this.name = name;
this.hometown = hometown;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getHometown(){
return hometown;
}
public void setHometown(String hometown){
this.hometown = hometown;
}
public String toString(){
return id + "\t" + name + "\t" + hometown;
}
}
class StudentRecord {
private static final String FILENAME = "students.dat";
private List<Stu> students;
public StudentRecord(){
students = new ArrayList<Stu>();
}
public void add(Stu s){
students.add(s);
}
public void delete(int id){
Iterator<Stu> iter = students.iterator();
while(iter.hasNext()){
Stu s = iter.next();
if(s.getId() == id){
iter.remove();
break;
}
}
}
public void modify(int id, String hometown){
for(Stu s : students){
if(s.getId() == id){
s.setHometown(hometown);
break;
}
}
}
public void save(){
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILENAME));
oos.writeObject(students);
oos.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void load(){
try{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILENAME));
students = (List<Stu>)ois.readObject();
ois.close();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public void displayAll(){
for(Stu s : students){
System.out.println(s);
}
}
public void searchById(int id){
boolean found = false;
for(Stu s : students){
if(s.getId() == id){
System.out.println(s);
found = true;
break;
}
}
if(!found){
System.out.println("No student with id " + id + " found.");
}
}
public void searchByName(String name){
boolean found = false;
for(Stu s : students){
if(s.getName().equals(name)){
System.out.println(s);
found = true;
}
}
if(!found){
System.out.println("No student with name " + name + " found.");
}
}
public void searchByHometown(String hometown){
boolean found = false;
for(Stu s : students){
if(s.getHometown().equals(hometown)){
System.out.println(s);
found = true;
}
}
if(!found){
System.out.println("No student from " + hometown + " found.");
}
}
public static void main(String[] args){
StudentRecord record = new StudentRecord();
Scanner scanner = new Scanner(System.in);
int choice = 0;
do{
System.out.println("1. Add student");
System.out.println("2. Delete student");
System.out.println("3. Modify student");
System.out.println("4. Display all students");
System.out.println("5. Search student by id");
System.out.println("6. Search student by name");
System.out.println("7. Search student by hometown");
System.out.println("8. Save to file");
System.out.println("9. Load from file");
System.out.println("0. Exit");
System.out.print("Your choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // consume newline
switch(choice){
case 1:
System.out.print("Enter student id: ");
int id = scanner.nextInt();
scanner.nextLine(); // consume newline
System.out.print("Enter student name: ");
String name = scanner.nextLine();
System.out.print("Enter student hometown: ");
String hometown = scanner.nextLine();
record.add(new Stu(id, name, hometown));
break;
case 2:
System.out.print("Enter student id: ");
id = scanner.nextInt();
record.delete(id);
break;
case 3:
System.out.print("Enter student id: ");
id = scanner.nextInt();
scanner.nextLine(); // consume newline
System.out.print("Enter new hometown: ");
hometown = scanner.nextLine();
record.modify(id, hometown);
break;
case 4:
record.displayAll();
break;
case 5:
System.out.print("Enter student id: ");
id = scanner.nextInt();
record.searchById(id);
break;
case 6:
System.out.print("Enter student name: ");
name = scanner.nextLine();
record.searchByName(name);
break;
case 7:
System.out.print("Enter hometown: ");
hometown = scanner.nextLine();
record.searchByHometown(hometown);
break;
case 8:
record.save();
break;
case 9:
record.load();
break;
case 0:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid choice.");
}
}while(choice != 0);
}
}
首先,我们可以设计一个Student类来存储每个学生的信息,包括学号、姓名、籍贯等属性。然后,我们可以使用Java的IO流来实现将学生信息保存到文件中以及从文件中读取学生信息。
以下是一个示例代码,实现了学生信息的创建、保存、读取以及按学号或姓名查询的功能。
import java.io.*;
import java.util.*;
public class Student {
private String ID;
private String name;
private String hometown;
public Student(String ID, String name, String hometown) {
this.ID = ID;
this.name = name;
this.hometown = hometown;
}
public String getID() {
return ID;
}
public String getName() {
return name;
}
public String getHometown() {
return hometown;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
List<Student> students = new ArrayList<>();
// 创建学生信息并保存到文件
System.out.println("请输入学生信息(学号 姓名 籍贯),输入exit结束:");
while (true) {
String input = sc.nextLine();
if (input.equals("exit")) {
break;
}
String[] info = input.split(" ");
Student student = new Student(info[0], info[1], info[2]);
students.add(student);
saveToFile(student);
}
// 从文件中读取学生信息
System.out.println("学生籍贯信息如下:");
BufferedReader br = new BufferedReader(new FileReader("students.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] info = line.split(" ");
Student student = new Student(info[0], info[1], info[2]);
students.add(student);
System.out.println(student.getHometown());
}
br.close();
for (Student student : students) {
// 按学号或姓名查询学生信息
if (student.getID().equals(query) || student.getName().equals(query)) {
System.out.println("请输入要查询的学号或姓名:");
String query = sc.nextLine();
System.out.println("学号:" + student.getID() + ",姓名:" + student.getName() + ",籍贯:" + student.getHometown());
}
}
}
private static void saveToFile(Student student) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt", true));
bw.write(student.getID() + " " + student.getName() + " " + student.getHometown());
bw.newLine();
bw.close();
}
}
在上面的代码中,我们先定义了一个Student类来存储学生信息。然后在main方法中,我们使用Scanner来读取用户输入的学生信息,并将每个学生信息保存到文件中。保存到文件的方法使用了Java的IO流中的BufferedWriter和FileWriter。
接着,我们使用BufferedReader和FileReader从文件中读取学生信息,并将每个学生信息保存到一个List中。在输出学生籍贯信息时,我们只需要遍历List并调用每个学生的getHometown方法即可。
最后,我们使用Scanner来读取用户输入的查询条件(学号或姓名),并在List中查找符合条件的学生信息。如果找到了符合条件的学生信息,我们就将学生的学号、姓名、籍贯输出给用户。
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
设计思路:
首先,我们需要定义一个学生类,包括学号、姓名、籍贯等信息;其次,我们需要定义一个贯籍类,用于存储各个籍贯;然后我们需要创建一个贯籍信息记录簿类,该类包括添加、删除、修改、查询等操作,同时也包括从磁盘文件读取和保存到磁盘文件的功能。
代码实现:
import os
import json
class Student:
def __init__(self, id, name, hometowm):
self.id = id
self.name = name
self.hometown = hometown
class Hometown:
def __init__(self, name):
self.name = name
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, student):
self.students.remove(student)
class RecordBook:
def __init__(self):
self.hometowns = []
def add_student(self, student):
hometown_exists = False
for hometown in self.hometowns:
if hometown.name == student.hometown:
hometown_exists = True
hometown.add_student(student)
break
if not hometown_exists:
new_hometown = Hometown(student.hometown)
new_hometown.add_student(student)
self.hometowns.append(new_hometown)
def remove_student(self, student):
for hometown in self.hometowns:
if hometown.name == student.hometown:
hometown.remove_student(student)
if len(hometown.students) == 0:
self.hometowns.remove(hometown)
def modify_student(self, student, new_hometown):
hometown_exists = False
for hometown in self.hometowns:
if hometown.name == student.hometown:
hometown.remove_student(student)
if len(hometown.students) == 0:
self.hometowns.remove(hometown)
if hometown.name == new_hometown:
hometown_exists = True
hometown.add_student(student)
break
if not hometown_exists:
new_hometown = Hometown(new_hometown)
new_hometown.add_student(student)
self.hometowns.append(new_hometown)
def search_by_id(self, id):
for hometown in self.hometowns:
for student in hometown.students:
if student.id == id:
return student
return None
def search_by_name(self, name):
students = []
for hometown in self.hometowns:
for student in hometown.students:
if student.name == name:
students.append(student)
return students
def search_by_hometown(self, hometown):
for h in self.hometowns:
if h.name == hometown:
return h.students
return []
def save_to_file(self, file_path):
dict = {}
for hometown in self.hometowns:
dict[hometown.name] = []
for student in hometown.students:
dict[hometown.name].append({"id": student.id, "name": student.name})
with open(file_path, 'w') as f:
json.dump(dict, f)
def read_from_file(self, file_path):
self.hometowns = []
with open(file_path, 'r') as f:
dict = json.load(f)
for hometown_name in dict.keys():
hometown = Hometown(hometown_name)
students = dict[hometown_name]
for student_dict in students:
student = Student(student_dict["id"], student_dict["name"], hometown_name)
hometown.add_student(student)
self.hometowns.append(hometown)
#创建学生信息并以磁盘文件保存
def create_student_and_save_to_file(rb, file_path):
id = input("请输入学号:")
name = input("请输入姓名:")
hometown = input("请输入籍贯:")
student = Student(id, name, hometown)
rb.add_student(student)
rb.save_to_file(file_path)
#读取磁盘文件并显示输出所有学生的籍贯信息
def display_hometowns_from_file(rb, file_path):
rb.read_from_file(file_path)
print("所有学生籍贯信息如下:")
for hometown in rb.hometowns:
print("籍贯:{},学生人数:{}".format(hometown.name, len(hometown.students)))
#按学号或姓名查询成绩
def search(rb):
option = input("请输入查询选项(1.按学号查询;2.按姓名查询):")
if option == "1":
id = input("请输入学号:")
student = rb.search_by_id(id)
if student:
print("查询成功,该学生籍贯为:{}".format(student.hometown))
else:
print("查询失败,未找到该学生")
elif option == "2":
name = input("请输入姓名:")
students = rb.search_by_name(name)
if len(students) > 0:
print("查询成功,共找到{}个学生,籍贯分别为:".format(len(students)))
for student in students:
print(student.hometown)
else:
print("查询失败,未找到该学生")
else:
print("输入有误,请重新输入")
#按籍贯查询并输出该籍贯的所有学生
def search_by_hometown(rb):
hometown = input("请输入籍贯:")
students = rb.search_by_hometown(hometown)
if len(students) > 0:
print("查询成功,共找到{}个学生,学号和姓名分别为:".format(len(students)))
for student in students:
print("{} {}".format(student.id, student.name))
else:
print("查询失败,未找到该籍贯的学生")
#能添加、删除和修改学生的籍贯信息
def modify(rb, file_path):
id = input("请输入学号:")
student = rb.search_by_id(id)
if not student:
print("修改失败,未找到该学生")
return
option = input("请输入修改选项(1.修改籍贯;2.删除学生):")
if option == "1":
new_hometown = input("请输入修改后的籍贯:")
rb.modify_student(student, new_hometown)
rb.save_to_file(file_path)
print("修改成功")
elif option == "2":
rb.remove_student(student)
rb.save_to_file(file_path)
print("删除成功")
else:
print("输入有误,请重新输入")
#测试
rb = RecordBook()
file_path = "./record_book.json"
while True:
print("请选择操作:")
print("1.创建学生信息并以磁盘文件保存")
print("2.读取磁盘文件并显示输出所有学生的籍贯信息")
print("3.按学号或姓名查询成绩")
print("4.按籍贯查询并输出该籍贯的所有学生")
print("5.能添加、删除和修改学生的籍贯信息")
print("0.退出程序")
option = input("请输入选项:")
if option == "1":
create_student_and_save_to_file(rb, file_path)
elif option == "2":
display_hometowns_from_file(rb, file_path)
elif option == "3":
search(rb)
elif option == "4":
search_by_hometown(rb)
elif option == "5":
modify(rb, file_path)
elif option == "0":
break
else:
print("输入有误,请重新输入")
以上为简单的学生贯籍信息记录簿的设计和实现,代码可以根据实际需求进行更改和完善。
如果我的回答解决了您的问题,请采纳!
自己动手做一做吧,有问题了再来问。
建议题主不要采纳那些问聊天机器人的
可以借鉴下
package student;
import java.util.Scanner;
import java.io.*;
public class jsb {
public static void main(String args[]) {
start();
}
static String []a=new String[100];
static void show(){
int o=0;
for(String i:a)
{
if (i==null)
{
break;
}
if(i.equals("0000"))
{
continue;
}
System.out.print(i+" ");
o++;
if (o%3==0)
{
System.out.println();
}
}
}
static void inquire(){
System.out.println("选择查询方式1:学号、2:姓名");
Scanner sc =new Scanner(System.in);
String xz = sc.next();
if(xz.equals("1")){
System.out.println("请输入查询的学号:");
xz = sc.next();
for(int i=0;i<a.length;i+=3){
if(a[i].equals("0000")) {
continue;
}
if(a[i].equals(xz))
{
System.out.println(a[i+2]);
break;
}
}
}
if(xz.equals("2")){
System.out.println("请输入查询的姓名:");
xz = sc.next();
for(int i=1;i<a.length;i+=3){
if(a[i].equals(xz))
{
System.out.println(a[i+1]);
break;
}
}
}
}
static void all(){
System.out.println("请输入查询的籍贯:");
Scanner sc =new Scanner(System.in);
String xz = sc.next();
System.out.println("学生姓名为:");
for(int i=2;i<a.length;i+=3){
if (a[i]==null)
{
System.out.println();
break;
}
if(a[i].equals(xz))
{
System.out.print(a[i-1]+" ");
}
}
}
static void add(){
System.out.println("请以空格隔开输入添加学生的信息(输入exit结束输入):");
Scanner sc=new Scanner(System.in);
String o;
String[][] k=new String[10][10];
for(int i=0;i<a.length;i++)
{
if(a[i]==null||a[i].equals("0000"))
{
o=sc.next();
if (o.equals("exit"))
{
System.out.println("添加成功!");
break;
}
k[0]=o.split(",");
a[i]=k[0][0];
a[i+1]=k[1][0];
a[i+2]=k[2][0];
}
}
}
static void delete() {
System.out.println("选择删除方式1:学号、2:姓名、3:籍贯");
Scanner sc =new Scanner(System.in);
String xz = sc.next();
if(xz.equals("1")){
System.out.println("请输入删除的学号:");
xz = sc.next();
for(int i=0;i<a.length;i+=3){
if(a[i].equals(xz))
{
a[i]="0000";
a[i+1]="0000";
a[i+2]="0000";
System.out.println("删除完成!");
break;
}
}
}
if(xz.equals("2")){
System.out.println("请输入删除的姓名:");
xz = sc.next();
for(int i=1;i<a.length;i+=3){
if (a[i]==null)
break;
if(a[i].equals(xz))
{
a[i]="0000";
a[i-1]="0000";
a[i+1]="0000";
System.out.println("删除完成!");
}
}
}
if(xz.equals("3")){
System.out.println("请输入删除的籍贯:");
sc =new Scanner(System.in);
xz = sc.next();
for(int i=2;i<a.length;i+=3){
if (a[i]==null)
{
System.out.println();
break;
}
if(a[i].equals(xz))
{
a[i]="0000";
a[i-1]="0000";
a[i-2]="0000";
System.out.println("删除完成!");
}
}
}
}
static void amend() {
System.out.println("请输入修改的学号!");
Scanner sc =new Scanner(System.in);
String xz = sc.next();
for(int i=0;i<a.length;i+=3){
if(a[i]==null)
break;
if(a[i].equals("0000")) {
continue;
}
if(a[i].equals(xz))
{
System.out.println("请输入修改后的姓名!!");
xz=sc.next();
a[i+1]=xz;
System.out.println("请输入修改后的籍贯!!");
xz=sc.next();
a[i+2]=xz;
break;
}
}
}
static void start(){
a[0]="2000";
a[1]="请问";
a[2]="河北";
a[3]="2001";
a[4]="温柔";
a[5]="山东";
a[6]="2002";
a[7]="儿童";
a[8]="广东";
a[9]="2003";
a[10]="任天野";
a[11]="河北";
a[12]="2004";
a[13]="体育";
a[14]="台湾";
boolean xh = true;
while(xh){
System.out.println("**欢迎进入学生籍贯信息记录簿**");
System.out.println("*1、显示学生信息 2、按学号或姓名查询其籍贯 3、按籍贯查询并输出该籍贯的所有学生 4、添加 5、删除 6、修改 7、退出程序 *");
Scanner sc =new Scanner(System.in);
int xz = sc.nextInt();
switch(xz){
case 1: show();
break;
case 2: inquire();
break;
case 3: all();
break;
case 4: add();
break;
case 5: delete();
break;
case 6: amend();
break;
case 7:
System.exit(0);
}
}
}
}