记录学了两个月Java的小练习,可供大家借鉴和改进,代码如下:
MainMenu,java
package com.itheima;
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
class IfIllegal {
//用于判断密码合理性
public boolean isAdminIllegal(String username) {
String regex = "[A]+(\\.*[0-9]){5}$";
boolean b = username.matches(regex);
return b;
}
public boolean isPasswordIllegal(String password) {
String regex = "\\w+(\\.*\\w){5,18}$";//与"[a-zA-Z0-9]{6,18}$"等效
boolean b = password.matches(regex);
return b;
}
}//正则表达式
class Grade {
public String toRank(double score) {
String str;
double grade=score/5;
if (grade > 100 || grade < 0) {
str = "ERROR";
} else {
switch ((int) grade/10) {
case 10:
case 9:
str = "优秀";
break;
case 8:
str = "良好";
break;
case 7:
case 6:
str = "合格";
break;
default:
str = "不合格";
}
}
return str;
}
}
public class MainMenu {
public static void main(String[] args) throws IOException {
char choice;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("=========欢迎来到学生成绩管理系统=========");
System.out.println("= 1.注册 =");
System.out.println("= =");
System.out.println("= 2.登录 =");
System.out.println("= =");
System.out.println("= 0.Exit =");
System.out.println("========================================");
System.out.println();
System.out.print("请选择:");
choice = scanner.next().charAt(0);
switch (choice) {
case '1':
Register();
break;
case '2':
Login();
break;
case '0':
System.out.println("已退出");
return;
default:
System.out.println("输入错误");
}
}
}
//注册模块
private static void Register() throws IOException {
Scanner scanner = new Scanner(System.in);
File admin = new File("D:\\Java Report\\admin.txt");
Admin adm = new Admin();
IfIllegal compare = new IfIllegal();
byte[] b = new byte[1024];//分配1kb的字节空间,用于写入文本
// String adminusername, password;
if (admin.getParentFile().exists() == false) {
admin.getParentFile().mkdir();
System.out.println("文件路径创建成功");
}//建立管理员文件路径
if (admin.exists() == false) {
admin.createNewFile();
System.out.println("用户配置文件创建成功");
}//建立管理员文件
//文件建立完创建流
FileInputStream filein1 = new FileInputStream(admin);//文件读取流,用于键值对读取文件
FileOutputStream fileout1 = new FileOutputStream(admin, true);
//以后也可以添加账户
Properties properties = new Properties();//创建字符串键值对,保存用户名-密码
properties.load(filein1);//读取admin文件的键值对
/*账户写入部分*/
System.out.print("请输入用户名(A+五个数字组成):");
adm.setAdminusername(scanner.next());
if (!compare.isAdminIllegal(adm.getAdminusername())) {
System.out.println("您输入的用户名不合法,请重新输入!");
return;
} else {
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
if (adm.getAdminusername().equals((String) enumeration.nextElement())) {
System.out.println("账号已存在,请勿重复注册!");
return;
}//判断账户存在合理性
}
}
System.out.print("请输入密码(6-18位组成):");
adm.setPassword(scanner.next());
if (!compare.isPasswordIllegal(adm.getPassword())) {
System.out.println("您输入的密码不合法,请重新输入!");
return;
} else {
properties.setProperty(adm.getAdminusername(), adm.getPassword());
String adname = properties.getProperty(adm.getAdminusername());//键-adname 用于遍历是否存在账号
b = (adm.getAdminusername() + " " + adm.getPassword() + "\n").getBytes();//这里的username用于匹配键值对的username
//获取输入用户名以及提示讯息的字节长度
//用户名和密码全部确认完毕后再写入
System.out.println("账户写入成功!");
System.out.println("密码录入成功!");
fileout1.write(b);//将b中的所有文本保存到admin文件内
fileout1.flush();
//关闭文件输入输出流
fileout1.close();
filein1.close();
System.out.println("账号已注册!");
}
}
//登录模块
private static void Login() throws IOException {
Scanner scanner = new Scanner(System.in);
boolean status = false;//登录状态
char choice;
while (true) {
System.out.println("=========欢迎来到学生成绩管理系统=========");
System.out.println("= 1.管理员登录 =");
System.out.println("= =");
System.out.println("= 2.学生查询 =");
System.out.println("= =");
System.out.println("= 0.Exit =");
System.out.println("========================================");
System.out.println();
System.out.print("请选择:");
choice = scanner.next().charAt(0);
switch (choice) {
case '1':
status = AdLog();
if (status == true) {
System.out.println("==============登录成功!已经进入学生管理系统!==============");
StudentManageSys();//学生管理系统
} else
System.out.println("登陆失败!");
break;
case '2':
StuCon();
break;
case '0':
System.out.println("已返回至主菜单");
return;
default:
System.out.println("输入错误");
}
}
}
//学生查询模块
private static void StuCon() throws IOException {
File students = new File("D:\\Java Report\\students.txt");
File studentscore = new File("D:\\Java Report\\studentscore.txt");
Scanner scanner = new Scanner(System.in);
String consult;
if (!students.exists()) {
System.out.println("查询失败:管理员还没有建立学生档案,请稍后再来");
return;
}
System.out.print("请输入您的姓名:");
consult = scanner.next();
FileInputStream fileread = new FileInputStream(students);//读取学生信息文件
FileInputStream fileread1 = new FileInputStream(studentscore);//读取学生分数文件
Properties properties = new Properties();
Properties properties1 = new Properties();
properties.load(fileread); //读取学生信息文件的键值对
properties1.load(fileread1); //读取学生分数键值对
Enumeration enumeration = properties.propertyNames();//遍历学生信息文件内的键值对
Enumeration enumeration1 = properties1.propertyNames();//遍历学生分数文件的键值对
while (enumeration.hasMoreElements()) {//遍历键值对的元素,如果有元素则一直遍历直到没有
String key = (String) enumeration.nextElement();
if (key.equals(consult)) {
String value = properties.getProperty(key);
System.out.println("您的学号和班级分别是:" + value);
//同时查询学生分数,由于不在同一个问价,因此需要内部遍历
while (enumeration1.hasMoreElements()) {
String key1 = (String) enumeration1.nextElement();
if (key1.equals(key)) {
String value1 = properties1.getProperty(key1);//value1是studentscore内学生姓名键的值
System.out.println("您的成绩是:" + value1);
}
}
System.out.println("查询成功!");
return;
}
}
System.out.println("查询失败:没有您的信息,请稍后再来");
}
//以下是管理员操作模块
private static boolean AdLog() throws IOException {
File admin = new File("D:\\Java Report\\admin.txt");
Scanner scanner = new Scanner(System.in);
boolean status = false; //登录状态是否正确
String password;
FileInputStream filein1 = new FileInputStream(admin);
Properties properties = new Properties();//创建字符串键值对,保存用户名-密码
properties.load(filein1);//读取admin文件的键值对
System.out.print("请输入用户名:");
String adname = scanner.next();//键-adname
String pass = properties.getProperty(adname);//值-password
System.out.print("请输入您账号的密码:");
password = scanner.next();
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {//遍历读取后的键值对
if (adname.equals((String) enumeration.nextElement())) {
System.out.println("已经查询到账号!");
if (password.equals(pass)) {
System.out.println("登录成功!");
status = true;
} else {
System.out.println("登陆失败:密码不匹配!");
}
}
}
return status;
}
/* 学生信息管理模块 */
private static void StudentManageSys() throws IOException {
Scanner scanner = new Scanner(System.in);
char choice;
while (true) {
System.out.println("=================欢迎来到简易学生管理系统==================");
System.out.println();
System.out.println(" 1.录入学生信息 ");
System.out.println();
System.out.println(" 2.删除学生信息 ");
System.out.println();
System.out.println(" 3.遍历学生信息 ");
System.out.println();
System.out.println(" 4.录入学生总分 ");
System.out.println();
System.out.println(" 5.学生总分排序 ");
System.out.println();
System.out.println(" 0.Exit ");
System.out.println("=========================================================");
System.out.println();
System.out.print("请选择:");
choice = scanner.next().charAt(0);
switch (choice) {
case '1':
StudentAdd();
break;
case '2':
StudentDel();
break;
case '3':
StudentPrt();
break;
case '4':
StudentSco();
break;
case '5':
StudentSor();
break;
case '0':
System.out.println("已返回至上级菜单");
return;
default:
System.out.println("输入错误");
}
}
}//学生管理系统主菜单
private static void StudentAdd() throws IOException {
Scanner scanner = new Scanner(System.in);
Student stu = new Student();
byte[] b = new byte[1024];
File students = new File("D:\\Java Report\\students.txt");
if (students.exists() == false) {
students.createNewFile();
System.out.println("学生信息文件创建成功!");
}
//字节流针对students文件
FileInputStream filein1 = new FileInputStream(students);
FileOutputStream fileout1 = new FileOutputStream(students, true);
Properties properties = new Properties();//用于遍历学生键值对
properties.load(filein1);//读取students键值对
System.out.print("请输入学生的姓名:");
stu.setName(scanner.next());
Enumeration enumeration = properties.propertyNames();//遍历students键,获取姓名
while (enumeration.hasMoreElements()) {
if (stu.getName().equals((String) enumeration.nextElement())) {
System.out.println("学生信息已存在,请勿重复写入!");
return;
}//判断合理性
}
System.out.print("请输入学生的学号:");
stu.setNumber(scanner.next());
System.out.print("请输入学生的班级(如果是新生则随机分配班级:new):");
stu.setClassroom(scanner.next());
if (stu.getClassroom().equals("new")) {
int distribute = 0;
Random random = new Random();
distribute = random.nextInt(3);
switch (distribute) {
case 0:
stu.setClassroom("2021 1Class");
break;
case 1:
stu.setClassroom("2021 2Class");
break;
case 2:
stu.setClassroom("2021 3Class");
break;
}
}//随机分配班级
//汇总写入学生信息
b = (stu.getName() + " " + stu.getNumber() + " " + stu.getClassroom() + "\n").getBytes();
fileout1.write(b);
fileout1.flush();
//输入完关闭数据流
fileout1.close();
filein1.close();
System.out.println("学生信息成功登入!");
stu.Info();
}//信息添加
private static void StudentDel() throws IOException {
Scanner scanner = new Scanner(System.in);
File students = new File("D:\\Java Report\\students.txt");
File temp = new File("D:\\Java Report\\temp.txt");
String delindex;//添加删除索引
if (temp.createNewFile() == true) {//创建临时文件
System.out.println("创建临时文件成功!");
}
System.out.print("请输入您要删除的学生的姓名:");
delindex = scanner.next();
FileInputStream filein1 = new FileInputStream(students);
Properties properties = new Properties();
properties.load(filein1);
//删除键值对
if (properties.containsKey(delindex)) {
properties.remove(delindex);
}
//将删除后的键值对写入临时文件
FileOutputStream fileouttem = new FileOutputStream(temp, false);
int len;
System.out.println("正在写入...");
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value = properties.getProperty(key);
byte[] b = new byte[1024];
b = (key + " " + value + "\n").getBytes();
fileouttem.write(b);
}
System.out.println("写入成功!");
//将临时文件写回student
FileInputStream fileintem = new FileInputStream(temp);
FileOutputStream fileout1 = new FileOutputStream(students, false);
byte[] b = "\n".getBytes();//换行符
while ((len = fileintem.read()) != -1) {//文件逐个读取
fileout1.write(len); //将temp文件写入students
}
//关闭文件流
filein1.close();
fileintem.close();
fileout1.close();
fileouttem.close();
temp.delete();//删除临时文件
}//信息删除
private static void StudentPrt() throws IOException {
File students = new File("D:\\Java Report\\students.txt");
FileInputStream fileread = new FileInputStream(students);
Properties properties = new Properties();
properties.load(fileread); //互殴students文本内的学生信息
System.out.println("文件读取成功!");
Enumeration enumeration = properties.propertyNames();//获取键值对键的名字
System.out.println("==============以下是学生信息================");
System.out.println("学生姓名 学号\t班级");
while (enumeration.hasMoreElements()) {//当键值对未遍历完成时
String key = (String) enumeration.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " " + value);
}
System.out.println("\n学生信息读取完毕!\n");
}//信息遍历
private static void StudentSco() throws IOException {
//利用students文件的键,转入studentscore文件
Scanner scanner = new Scanner(System.in);
File studentscore = new File("D:\\Java Report\\studentscore.txt");//学生成绩文件
File students = new File("D:\\Java Report\\students.txt");
StudentException stu = new StudentException();
Grade grade = new Grade();
String name;
double[] score = new double[5];//5门课
double sum = 0;//单科成绩和总成绩
System.out.print("请输入需要登入学生的姓名:");
name = scanner.next();
if (!studentscore.exists()) {
studentscore.createNewFile();
System.out.println("学生分数文件创建成功!");
}
FileInputStream filein1 = new FileInputStream(students);//filein1读取students
FileInputStream filein2 = new FileInputStream(studentscore);
FileOutputStream fileout2 = new FileOutputStream(studentscore, true);
Properties properties = new Properties();
Properties properties1 = new Properties();
properties.load(filein1);//读取students键值对
properties1.load(filein2);//读取students键值对,判断合理性
Enumeration enumeration1 = properties1.propertyNames();
while (enumeration1.hasMoreElements()) {
if (name.equals((String) enumeration1.nextElement())) {
System.out.println("学生信息已存在,请勿重复写入!");
return;
}//判断账户存在合理性
}
Enumeration enumeration = properties.propertyNames();//遍历students键,获取姓名
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
if (key.equals(name)) {
for (int i = 0; i < 5; i++) {
System.out.printf("请输入学生 %s 的第 %d 门课的成绩:", name, i + 1);
score[i] = scanner.nextDouble();
sum += score[i];
}
System.out.print("请输入学生的扣分情况:");
stu.setDeduct(scanner.nextFloat());
System.out.print("请输入学生的加分情况:");
stu.setBonus(scanner.nextFloat());
stu.setScore(sum - stu.getDeduct() + stu.getBonus());//计算出最终结果
byte[] b = new byte[1024];
b = ("\n" + key + " " + stu.getScore()).getBytes();//将学生的姓名和成绩写入
fileout2.write(b);
System.out.println("成绩已经写入!");
//展示输入的情况、核对
System.out.printf("学生姓名:%s\n第一门\t第二门\t第三门\t第四门\t第五门\t总分\t等第\n", name);
for (int i = 0; i < 5; i++) {
System.out.printf("%.2f\t", score[i]);
}
System.out.print(sum + "\t");
System.out.println(grade.toRank(sum));
filein1.close();
fileout2.close();
return;
}
}
System.out.println("成绩写入失败:未查询到学生姓名!");
}//分数添加
private static void StudentSor() throws IOException {
File studentscore = new File("D:\\Java Report\\studentscore.txt");
String[] name = new String[100];
double[] sort = new double[100];
int i = 0, j, len;
double sum = 0;
int count = 0;
if (!studentscore.exists()) {
System.out.println("登入失败:学生分数文件不存在!");
return;
}//合理性判断
FileInputStream filein1 = new FileInputStream(studentscore);
Properties properties = new Properties();
properties.load(filein1);
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
double value = Double.parseDouble(properties.getProperty(key));//字符串转数字
name[i] = key;
sort[i] = value;
sum += sort[i];
i++;
}
len = i;
//选择排序算法
for (i = 0; i < len; i++) {
int max = i;
for (j = i + 1; j < len; j++) {
if (sort[max] < sort[j]) {
max = j;
}
}
//交换姓名与分数
double tempscore = sort[max];
String tempname = name[max];
sort[max] = sort[i];
name[max] = name[i];
sort[i] = tempscore;
name[i] = tempname;
}
//输出结果
System.out.println("学生排名\t学生姓名\t学生成绩");
for (i = 0; i < len; i++) {
System.out.printf("第%d名\t%s\t%.2f\n", i + 1, name[i], sort[i]);
if (sort[i] >= (sum / len)) {
count++;
}
}
System.out.printf("班级本次的平均分为 %.2f\t总共有 %d 人高于平均分\n", sum / len, count);
filein1.close();
}//学生排名
}
//总结:
//写文件键值对时候,最后一定要加一个回车键
//文件读取需要输入流,读取键值对需要Properties.load方法
//写入文件时需要输出流out,可遍历循环输出
Student.java
package com.itheima;;
public class Student {
//学生对象的主体,包含姓名,学号,班级,分数
private String name;
private String number;
private String classroom;
private double score;
//可以通过输入来存入
public Student() {
}
//get set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
//成员变量
public void Info() {
System.out.printf("学生信息(姓名:%s 学号:%s 班级:%s )已经登入学生档案!\n", this.getName(), this.getNumber(),this.getClassroom());
}
}
Admin.java
package com.itheima;
public class Admin {
private String adminusername="none";
private String password="none";
public Admin() {
}
public String getAdminusername() {
return adminusername;
}
public void setAdminusername(String adminusername) {
this.adminusername = adminusername;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//成员方法用于验证
public void Info(){
System.out.printf("账号:%s,密码:%s\n",this.getAdminusername(),this.getPassword());
}
}
StudentException.java
package com.itheima;
public class StudentException extends Student{
//成员方法--加分项、扣分项
private double bonus;
private double deduct;
//构造方法
public StudentException() {
}
//get set
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public double getDeduct() {
return deduct;
}
public void setDeduct(double deduct) {
this.deduct = deduct;
}
}