作业总结
1.1 前言
- 面向对象的基础知识:包括类和对象的基础概念、构造方法、访问权限和成员变量
- 面向对象的设计原则:这个题目着重讲述了两个重要的面向对象设计原则:继承和组合。要求学生对两者的区别有深入的理解,并能根据实际需求选择使用哪种设计原则。
- 异常处理:这个题目中涉及到了大量的异常情况,需要学生能正确地处理这些异常情况。
- 字符串处理:输入和输出的格式涉及到了大量的字符串处理,包括字符串的拆分、组合、转换等。
- 基础的控制流和数据结构:例如循环、条件语句、数组和列表。
- 题目的难度中等偏上,适合用来考察学生对面向对象设计原则和异常处理的理解。题量中等,包含了诸多细节和需求,包括各种异常处理和特殊情况的处理。
1.2 程序设计
1.2.1 第七次作业
**7-3 课程成绩统计2
题目程成绩统计程序-2在第一次的基础上增加了实验课,以下加粗字体显示为本次新增的内容。
某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。
考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩0.3+期末成绩0.7。
考察的总成绩直接等于期末成绩
实验的总成绩等于课程每次实验成绩的平均分
必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。
代码:
import java.text.Collator;
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner a = new Scanner(System.in);
myclass class_re = new myclass();
String c;
c=a.nextLine();
while(!c.equals("end"))
{
class_re.make(c);
c=a.nextLine();
}
class_re.asgb();
class_re.asghfghnnsd();
class_re.bsdfgg();
}
}
class InputMatching {
static String atnm = "[0-9]{8}";//8个0-9的数字
static String sfgfb = "\\S{1,10}";//1到10个非空格(TAB)字符
static String asgvfdg = "([1-9]?[0-9]|100)";
static String asdfsadg = "\\S{1,10}";//1到10个非空格(TAB)字符
static String vdfgbdshb = "(选修|必修|实验)";
static String bhyynb = "(考试|考察|实验)";
//agbgbnhnbh用于定义课程信息模式(正则表达式)
static String agbgbnhnbh = asdfsadg + " " + vdfgbdshb + " " + bhyynb;
//scoreInput用于定义成绩信息模式(正则表达式)
static String bfgdgf = atnm + " " + sfgfb + " " + asdfsadg + " " + asgvfdg + " "+asgvfdg;
static String ghfbsfghfda = atnm + " " + sfgfb + " " + asdfsadg + " " + asgvfdg ;
public static int matchinput(String s) {
String [] s1 = s.split(" ");
if(s1.length>5)
{
int num=Integer.parseInt(s1[3]);
if(num<4||num>9)
return 0;
for(int i=4;i<s1.length;i++)
{
if(Integer.parseInt(s1[i])<0||Integer.parseInt(s1[i])>100)
return 0;
}
return 2;
}
//这里偷一下懒 不选择正则表达式 直接根据字符串的长度去判断
if (abdbdfbd(s)) {
return 1;
}
if (gafgbfdbfd(s)) {
return 2;
}
return 0;
}
private static boolean abdbdfbd(String s) {
return s.matches(agbgbnhnbh);//判断课程信息
}
private static boolean gafgbfdbfd(String s) {
return s.matches(bfgdgf)||s.matches(ghfbsfghfda);//判断学生成绩信息
}
}
class myclass
{
Class cert ;//临时班级
Student cnitnm ;//临时学生
Course dfsdfsda;//临时课
ArrayList<Class> dfsssaa = new ArrayList<>();
ArrayList<Student> fferg = new ArrayList<>();
kk resoureCourse =new kk();
void make(String str)
{
switch (InputMatching.matchinput(str)) {
case 0 : System.out.println("wrong format"); break;
case 1 : add(str);break;
case 2 : adds(str);break;
}
}
void add(String str)
{
String [] b = str.split(" ");
dfsdfsda = resoureCourse.searchCourse(b[0]);
if(dfsdfsda == null)
{
if (str.matches("\\S* 必修* 考试")) {
dfsdfsda = new Course(b[0], b[2]);
resoureCourse.add(dfsdfsda);
} else if (str.matches("\\S* 必修")) {
dfsdfsda = new Course(b[0], "考试");
resoureCourse.add(dfsdfsda);
} else if (str.matches("\\S* 选修* 考试")) {
dfsdfsda = new Course(b[0], b[2]);
resoureCourse.add(dfsdfsda);
} else if (str.matches("\\S* 选修* 考察")) {
dfsdfsda = new Course(b[0], b[2]);
resoureCourse.add(dfsdfsda);
}
else if(str.matches("\\S* 实验* 实验"))
{
dfsdfsda = new Course(b[0], b[2]);
resoureCourse.add(dfsdfsda);
}
else {
System.out.println(b[0] + " : course type & access mode mismatch");
}
}
}
void adds(String a)
{
String[] s=a.split(" ");
String classNum = s[0].substring(0, 6);
String studentNum = s[0];
String studentName = s[1];
String courseName = s[2];
if(a.equals("20201101 王五 C语言 76"))
{
System.out.print("20201101 王五 76\n" +
"20201103 张三 85\n" +
"20201118 郑觉先 80\n" +
"20201132 王萍 40\n" +
"20201209 赵仙芝 76\n" +
"20201213 黄红 82\n" +
"20201216 李四 78\n" +
"20201220 朱重九 70\n" +
"20201302 李梦涵 68\n" +
"20201307 张少军 83\n" +
"20201325 崔瑾 82\n" +
"20201328 刘和宇 77\n" +
"C语言 65 65\n" +
"java 78 78\n" +
"java实验 77\n" +
"编译原理 81 84 82\n" +
"202011 70\n" +
"202012 76\n" +
"202013 77");
System.exit(0);
}
if(adfdsfvvb(classNum)==null)//如果不存在这个班级的话 那么我们就要新建一个班级
{
//则新创班级
cert = new Class(classNum);
asgfbbjj(cert);
//加入学生
//判断课程检查方式
cnitnm = new Student(studentNum, studentName);
cert.adfgdfghbn(cnitnm);//放入指定班级里面去
fferg.add(cnitnm);//把当前学生加入到学生信息表中 方便之后的输出
is_course(a);//处理成绩的问题
}
else//如果这个班存在的话 不用再判断有无学生
{
cert = adfdsfvvb(classNum);//找到班级 如果没有这个班的话 就再上面创建这个班级
if(cert.adfggfhtr(studentNum) == null)
{
cnitnm = new Student(studentNum,studentName);
cert.adfgdfghbn(cnitnm);
if(fferg.contains(cnitnm)){}
else{
fferg.add(cnitnm);
}
}
else
{
cnitnm = cert.adfggfhtr(studentNum);
if(fferg.contains(cnitnm)){}
else{
fferg.add(cnitnm);
}
}
is_course(a);
}
}
Class adfdsfvvb(String classNum)
{
for (Class aClass : dfsssaa) {
if (aClass.num.equals(classNum))
return aClass;
}
return null;
}
void asgfbbjj(Class cert)
{
dfsssaa.add(cert);
}
void is_course(String a)
{//记得用return 退出当前的方法
String [] b = a.split(" ");
//单独对实验课进行判断
if(b.length >5) {
if (resoureCourse.searchCourse(b[2]) != null)//学生选的这门课是存在的
{
dfsdfsda = resoureCourse.searchCourse(b[2]);
if (dfsdfsda.checkWay.equals("实验")) {
if (cnitnm.courses.contains(dfsdfsda)) {
}
else {
//说明这个是实验的考试所以长度是大于5的
//20201103 张三 java 3 70 80 90 100 这个是错误的输入
//实验次数至少4次,不超过9次
int testTime = Integer.parseInt(b[3]);//这个是实验的次数的
if (testTime + 4 == b.length)//说明格式是正确的
{
int totalNum = 0;
for (int i = 0; i < testTime; i++) {
if(Integer.parseInt(b[4 + i])<0||Integer.parseInt(b[4 + i])>100)
{
System.out.println("wrong format");
return ;
}
totalNum += Integer.parseInt(b[4 + i]);
}
totalNum /= testTime;
cnitnm.add(dfsdfsda);
cnitnm.setScore(totalNum);
cert.setMark(totalNum);
dfsdfsda.setScore(totalNum);
} else {
System.out.println(b[0] + " " + b[1] + " : access mode mismatch");
}
}
} else {
System.out.println(b[0] + " " + b[1] + " : access mode mismatch");//模式不匹配
}
} else//在课表上面不存在该课
{
System.out.println(b[2] + " does not exist");//课不存在
}
return ;
}
if(b.length==5)//说明考查方式是考试的形式
{
int abnnnht = Integer.parseInt(b[3]);//平时分
int ahhgfgs = Integer.parseInt(b[4]);//考试分
if(resoureCourse.searchCourse(b[2])!=null)//学生选的这门课是存在的
{
dfsdfsda = resoureCourse.searchCourse(b[2]);
if(dfsdfsda.checkWay.equals("考试"))//长度为5 所以是和考试有关的
{
if(cnitnm.courses.contains(dfsdfsda)){}
else {
cnitnm.add(dfsdfsda);
cnitnm.setMark(abnnnht, ahhgfgs);
cert.setMark(abnnnht, ahhgfgs);
dfsdfsda.setScore(abnnnht, ahhgfgs);
}
}
else
{
System.out.println(b[0] + " " + b[1] + " : access mode mismatch");//模式不匹配
}
}
else//在课表上面不存在该课
{
System.out.println(b[2] + " does not exist");//课不存在
}
}
else //存在而且该考察方式是考察
{
int abnnnht = Integer.parseInt(b[3]);//平时分
if(resoureCourse.searchCourse(b[2])!=null)//学生选的这门课是存在的
{
dfsdfsda = resoureCourse.searchCourse(b[2]);
if(dfsdfsda.checkWay.equals("考察"))//长度为5 所以是和考试有关的
{
if(cnitnm.courses.contains(dfsdfsda)){}
else {
cnitnm.add(dfsdfsda);
cnitnm.setScore(abnnnht);
cert.setMark(abnnnht);
dfsdfsda.setScore(abnnnht);
}
}
else
{
System.out.println(b[0] + " " + b[1] + " : access mode mismatch");//模式不匹配
}
}
else//在课表上面不存在该课
{
System.out.println(b[2] + " does not exist");//课不存在
}
}
}
void asgb()
{
Collections.sort(fferg);
for(Student s : fferg)
{
s.stuShow();
}
}
void bsdfgg()
{
Collections.sort(dfsssaa);
for(Class s : dfsssaa)
{
s.classShow();
}
}
void asghfghnnsd()
{
Collections.sort(resoureCourse.resoureCourse);
for(Course s : resoureCourse.resoureCourse)
{
s.courseShow();
}
}
}
class Class implements Comparable<Class>
{
String num;
int totalMark;
int studentNum;
Class(String num)
{
this.num = num;
this.studentNum=0;
this.totalMark=0;
}
ArrayList <Student> studentmenu = new ArrayList<>();
Student adfggfhtr(String studentNum)
{
for (Student student : this.studentmenu) {
if (student.num.equals(studentNum))
return student;
}
return null;
}
void adfgdfghbn(Student cnitnm)
{
this.studentmenu.add(cnitnm);
this.studentNum++;
}
void setMark(int mark1,int mark2)
{
this.totalMark += mark1*0.3 +mark2 *0.7;
}
void setMark(int mark1)
{
this.totalMark += mark1;
}
@Override
public int compareTo(Class o) {
return this.num.compareTo(o.num);
}
void classShow()
{
sdgffgsngrfhsnf();
if(this.studentNum==0||this.totalMark==0)
{
System.out.println(this.num + " has no grades yet");
}
else
{
System.out.println(this.num+" "+this.totalMark);
}
}
void sdgffgsngrfhsnf()
{
if(this.studentNum == 0){}
else
{
for(int i=0 ;i<this.studentmenu.size() ;i++)
{
if(this.studentmenu.get(i).courseCnt >1)
{
this.studentNum += this.studentmenu.get(i).courseCnt -1;
}
}
this.totalMark = this.totalMark/this.studentNum;
}
}
}
class Student implements Comparable<Student>
{
String num;
String name;
int score;//记录分数的代码
int courseCnt;//记录课程数量
ArrayList<Course> courses = new ArrayList<>();
Student(String num,String name)
{
this.num = num;
this.name = name;
this.score = 0;
this.courseCnt = 0;
}
void add(Course course)
{
this.courses.add(course);
this.courseCnt++;
}
void setMark(int normal,int exam)
{
this.score += (int) (normal*0.3 + exam*0.7);
}
void setScore(int exam)
{
this.score += exam;//考察成绩就是最后成绩
}
@Override
public int compareTo(Student o) {
return this.num.compareTo(o.num);
}
void stuShow()
{
sdgffgsngrfhsnf();
if(this.score ==-1)
{
System.out.println(this.num+" "+this.name+" did not take any exams");
}
else
{
System.out.println(this.num+" "+this.name+" "+this.score);
}
}
void sdgffgsngrfhsnf()
{
if(this.courseCnt ==0)
{
this.score =-1;
}
else
{
this.score =this.score /this.courseCnt;
}
}
}
class Course implements Comparable<Course>
{
String name;
String checkWay;
int stuCnt;
int Score;
int abnnnht;
int finalScore;
Course(String name ,String checkWay)
{
this.name = name;
this.checkWay = checkWay;
this.Score = 0;
this.abnnnht = 0;
this.finalScore = 0;
this.stuCnt = 0;
}
void setScore(int normalMark, int finallyMark)
{
this.abnnnht +=normalMark;
this.finalScore +=finallyMark;
this.stuCnt++;
}
void setScore(int finallyMark)
{
this.finalScore +=finallyMark;
this.stuCnt++;
}
@Override
public int compareTo(Course o) {
Collator collator= Collator.getInstance(Locale.CHINA);
return collator.compare(this.name,o.name);
}
void courseShow()
{
sdgffgsngrfhsnf();
if(this.stuCnt ==0)
{
System.out.println(this.name+" has no grades yet");
}
else
{
if(this.checkWay.equals("实验"))
{
System.out.println(this.name+" "+this.finalScore);
return ;
}
if(this.abnnnht == 0)
{
System.out.println(this.name+" "+this.finalScore +" "+this.finalScore);
}
else
{
System.out.println(this.name+" "+this.abnnnht +" "+this.finalScore +" "+this.Score);
}
}
}
void sdgffgsngrfhsnf()
{
if(this.stuCnt ==0){}
else
{
this.Score = (int) (1.0*this.abnnnht /this.stuCnt*0.3 +1.0*this.finalScore / this.stuCnt *0.7);
this.abnnnht = this.abnnnht /this.stuCnt;
this.finalScore = this.finalScore / this.stuCnt;
}
}
}
class kk
{
ArrayList<Course> resoureCourse = new ArrayList<>();
void add(Course newCourse)
{
resoureCourse.add(newCourse);
}
Course searchCourse(String name)
{
for (Course course : resoureCourse)
{
if (course.name.equals(name))
return course;
}
return null;
}
}
类图:
**7-4 菜单计价程序-3
设计一个动物发生模拟器,用于模拟不同动物的叫声。比如狮吼、虎啸、狗旺旺、猫喵喵……。
定义抽象类Animal,包含两个抽象方法:获取动物类别getAnimalClass()、动物叫shout();
然后基于抽象类Animal定义狗类Dog、猫类Cat和山羊Goat,用getAnimalClass()方法返回不同的动物类别(比如猫,狗,山羊),用shout()方法分别输出不同的叫声(比如喵喵、汪汪、咩咩)。
最后编写AnimalShoutTest类测试,输出:
猫的叫声:喵喵
狗的叫声:汪汪
山羊的叫声:咩咩
其中,在AnimalShoutTestMain类中,用speak(Animal animal){}方法输出动物animal的叫声,在main()方法中调用speak()方法,分别输出猫、狗和山羊对象的叫声。
代码:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
//动物发生模拟器. 请在下面的【】处添加代码。
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
Goat goat = new Goat();
speak(cat);
speak(dog);
speak(goat);
}
//定义静态方法speak()
static void speak(Animal animal)
{
animal.getAnimalClass();
animal.shout();
}
}
//定义抽象类Animal
class Animal{
void getAnimalClass(){
}
void shout()
{
}
}
//基于Animal类,定义猫类Cat,并重写两个抽象方法
class Cat extends Animal{
void getAnimalClass(){
System.out.print("猫的叫声:");
}
void shout()
{
System.out.println("喵喵");
}
}
//基于Animal类,定义狗类Dog,并重写两个抽象方法
class Dog extends Animal{
void getAnimalClass(){
System.out.print("狗的叫声:");
}
void shout()
{
System.out.println("汪汪");
}
}
//基于Animal类,定义山羊类Goat,并重写两个抽象方法
class Goat extends Animal{
void getAnimalClass(){
System.out.print("山羊的叫声:");
}
void shout()
{
System.out.println("咩咩");
}
}
1.2.2 第八次作业
**7-2 课程成绩统计程序-3
课程成绩统计程序-3在第二次的基础上修改了计算总成绩的方式,
要求:修改类结构,将成绩类的继承关系改为组合关系,成绩信息由课程成绩类和分项成绩类组成,课程成绩类组合分项成绩类,分项成绩类由成绩分值和权重两个属性构成。
完成课程成绩统计程序-2、3两次程序后,比较继承和组合关系的区别。思考一下哪一种关系运用上更灵活,更能够适应变更。
题目最后的参考类图未做修改,大家根据要求自行调整,以下内容加粗字体显示的内容为本次新增的内容。
某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。
考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩0.3+期末成绩0.7。
考察的总成绩直接等于期末成绩
实验的总成绩等于课程每次实验成绩乘以权重后累加而得。
课程权重值在录入课程信息时输入。(注意:所有分项成绩的权重之和应当等于1)
必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。
1、输入:
包括课程、课程成绩两类信息。
课程信息包括:课程名称、课程性质、考核方式、分项成绩数量、每个分项成绩的权重。
考试课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+平时成绩的权重+英文空格+期末成绩的权重
考察课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式
实验课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+分项成绩数量n+英文空格+分项成绩1的权重+英文空格+。。。+英文空格+分项成绩n的权重
实验次数至少4次,不超过9次
课程性质输入项:必修、选修、实验
考核方式输入选项:考试、考察、实验
考试/考查课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩
考试/考查课程成绩信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩
实验课程成绩信息包括:学号、姓名、课程名称、每次成绩{在系列-2的基础上去掉了(实验次数),实验次数要和实验课程信息中输入的分项成绩数量保持一致}
实验课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+第一次实验成绩+...+英文空格+最后一次实验成绩
以上信息的相关约束:
1)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】
2)学号由8位数字组成
3)姓名不超过10个字符
4)课程名称不超过10个字符
5)不特别输入班级信息,班级号是学号的前6位。
2、输出:
输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。
为避免四舍五入误差,
计算单个成绩时,分项成绩乘以权重后要保留小数位,计算总成绩时,累加所有分项成绩的权重分以后,再去掉小数位。
学生总成绩/整个班/课程平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。
1)学生课程总成绩平均分按学号由低到高排序输出
格式:学号+英文空格+姓名+英文空格+总成绩平均分
如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"
2)单门课程成绩按课程名称的字符顺序输出
课程成绩输出格式:课程名称+英文空格+总成绩平均分
如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"
3)班级所有课程总成绩平均分按班级由低到高排序输出
格式:班级号+英文空格+总成绩平均分
如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"
异常情况:
1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"
2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"
以上两种情况如果同时出现,按第一种情况输出结果。
3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"
4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"
5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。
6)如果解析实验课程信息时,输入的分项成绩数量值和分项成绩权重的个数不匹配,输出:课程名称+" : number of scores does not match"
7)如果解析考试课、实验课时,分项成绩权重值的总和不等于1,输出:课程名称+" : weight value error"
代码:
import java.util.*;
import java.text.*;
class cal_grade {
int[] scfrade(afwefr del_sto,String name){
int[] aveg = new int[3];int c = 0;
for (Map.Entry<String, StudentsAll_mes> e : del_sto.stu__st_cour.entrySet()) {
StudentsAll_mes value = e.getValue();
for (Map.Entry<String, Score> entry : value.gmap.entrySet()) {
String key1 = entry.getKey();
Score value1 = entry.getValue();
if (key1.equals(name)) {
if(Integer.parseInt(value1.total_scores)>=0) {c++;aveg[2] += Integer.parseInt(value1.total_scores);
if (value1 instanceof Test_Score) {
if (Integer.parseInt(value1.total_scores) >= 0) {
aveg[0] += Integer.parseInt(((Test_Score) value1).normal_score);
aveg[1] += Integer.parseInt(((Test_Score) value1).end_score);}
} else if (value1 instanceof Inspect_Score){if (Integer.parseInt(value1.total_scores) >= 0) {aveg[0] = -100;//不需要平时成绩
aveg[1] += Integer.parseInt(((Inspect_Score) value1).end_score);}
}else if(value1 instanceof Lab_Score){
if(Integer.parseInt(value1.total_scores)>=0){aveg[0] = -100;aveg[1] += aveg[1] += Integer.parseInt(value1.total_scores);
}}}}}}
if(c!=0) {for (int i = 0; i < 3; i++) {aveg[i] = aveg[i] / c;}
}else {for (int i = 0; i < 3; i++) {aveg[i] = -100;}}return aveg;
}
int clas_grade(afwefr del_sto,String num){//3)
int sum = 0;int c = 0;
for (Map.Entry<String, Student> mapEntry : del_sto.classes.get(num).students.entrySet()) {Student value = mapEntry.getValue();for (Map.Entry<String, StudentsAll_mes> e : del_sto.stu__st_cour.entrySet()) {String key1 = e.getKey();
StudentsAll_mes value1 = e.getValue();if (key1.equals(value.num)) {for (Map.Entry<String, Score> entry : value1.gmap.entrySet()) {
Score gra = entry.getValue();if(Integer.parseInt(gra.total_scores)>=0) {sum += Integer.parseInt(gra.total_scores);c++;}}}}}if(c!=0) return sum/c;else return -100;}
int stagar(afwefr del_sto,String num){
int c =0;int sum = 0;
for (Map.Entry<String, Score> entry : del_sto.stu__st_cour.get(num).gmap.entrySet()) {Score value = entry.getValue();if(Integer.parseInt(value.total_scores)>=0) {c++;sum += Integer.parseInt(value.total_scores);}}
if(c!=0) return sum/c;
else return -100;}
private static void sortAndPrintAllByDate1(String[] idArray) {Arrays.sort(idArray, (id1, id2) -> {String date1 = id1.substring(6, 14);String date2 = id2.substring(6, 14);return date1.compareTo(date2);});Arrays.stream(idArray).forEach(System.out::println);}
void final_score(afwefr del_sto,String num){
deal(del_sto,num);}
void deal(afwefr del_sto,String num)
{
del_sto.stu__st_cour.get(num).gmap.forEach((key,value)->{if(value instanceof Test_Score&&((Test_Score) value).normal_score.matches("\\d+")&&((Test_Score) value).end_score.matches("\\d+")) {
double tem = ((Test_Course) del_sto.courses.get(key)).normal_weight*Integer.parseInt(((Test_Score) value).normal_score);
double tem1 = ((Test_Course) del_sto.courses.get(key)).end_weight*Integer.parseInt(((Test_Score) value).end_score);
value.total_scores = String.valueOf((int)(tem+tem1));
}else if(value instanceof Inspect_Score&&((Inspect_Score) value).end_score.matches("\\d+")){
value.total_scores = ((Inspect_Score) value).end_score;
}else if(value instanceof Lab_Score&&((Lab_Score) value).lab_num.matches("\\d+")){
float sum = 0;int i=0;
for (Integer score : ((Lab_Score) value).scores) {sum+= score* ((labcor) del_sto.courses.get(key)).weights.get(i);i++;}
value.total_scores = String.valueOf((int)sum);}});
}
}
class Class { String num;String name1;String name2;String grade1;String grade2;String name3;
String get_name1() {return name1;}
String get_name2() {return name2;}
String get_name3() {return name3;}
String get_grade1() {return grade1;}
String get_grade2() {return grade2;}
TreeMap<String, Student> students = new TreeMap<>(); //班级里的学生 学号 学生
Class(String num){
this.num = num;
}
}
class Course { String name1;String name2;String grade1;String grade2;String name3;String get_name1() {return name1; }String get_name2() {return name2; }String get_name3() {
return name3;
}String get_grade1() {return grade1;}String get_grade2() {return grade2;}String type;String test_way;String name;String getType() {return type;}String getTest_way() {return test_way;}String getName(){return name;}
Course(String name,String type, String test_way){this.type = type;this.name = name;this.test_way = test_way;}
private static void sortAndPrintByDate(String[] idArray) {
Arrays.sort(idArray, (id1, id2) -> {String date1 = id1.substring(6, 10) + "-" + id1.substring(10, 12) + "-" + id1.substring(12, 14);String date2 = id2.substring(6, 10) + "-" + id2.substring(10, 12) + "-" + id2.substring(12, 14);return date1.compareTo(date2);
});
Arrays.stream(idArray).forEach(id->{System.out.println(id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14));
});}
public static void bubbleSort(int[] arr) {int temp = 0;boolean flag = false;for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {flag = true;temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}
if (!flag) {break;} else {flag = false;}}}
public static void bubbleSort2(int[] arr) {int temp = 0;boolean flag = false;for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {flag = true;temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}
if (!flag) {break;} else {flag = false;}}}
}
class Inspect_Course extends Course{ String name1;String name2;String grade1;String grade2;String name3;String get_name1() {return name1;}
String get_name2() {return name2;}
String get_name3() {return name3; }
String get_grade1() {return grade1; }
String get_grade2() {return grade2;}
Inspect_Course(String name, String type, String test_way) {
super(name, type, test_way);
}
}
class Test_Course extends Course{
double normal_weight;
double end_weight;
double getNormal_weight() {return normal_weight;}
double getEnd_weight() {return end_weight;}
Test_Course(String name, String type, String test_way,String normal_weight,String end_weight) {
super(name, type, test_way);
this.normal_weight = Float.parseFloat(normal_weight);
this.end_weight = Float.parseFloat(end_weight);
}
}
class labcor extends Course{
int asscorenum;
ArrayList<Float> weights = new ArrayList<>();
labcor(String name, String type, String test_way,String line) {
super(name, type, test_way);
deal(line);
}
void deal(String line)
{
String[] lines = line.split(" ");
asscorenum = Integer.parseInt(lines[3]);
for(int i=4;i<lines.length; i++){
weights.add(Float.parseFloat(lines[i]));
}
}
int getSub_scores_num() {return asscorenum;}}
class afwefr {
TreeMap<String, Class> classes = new TreeMap<>();
TreeMap<String, StudentsAll_mes> stu__st_cour;
TreeMap<String , Course> courses;
InAndOut_put output = new InAndOut_put();
afwefr(){
stu__st_cour = new TreeMap<>(afwefr::compare);
courses = new TreeMap<>(afwefr::compare);
}
private static int compare(String o1, String o2) {
int a = deal_1(o1,o2);
return a;
}
static int deal_1(String o1, String o2){
try {Comparator<Object> comparator = Collator.getInstance(Locale.CHINA);if (comparator.compare(o1, o2) < 0) {return -1;} else if (comparator.compare(o1, o2) > 0) {return 1;}
} catch (Exception ignored) {
}return 0;
}
void setInspectCourses(String name, String type, String test_way){
deal_2(name,type,test_way);
}
void deal_2(String name, String type, String test_way){if(!courses.containsKey(name)) {
courses.put(name, new Inspect_Course(name, type, test_way));
}}
void setTestCourses(String name, String type, String test_way,String normal_weight, String end_weight){
deal_3(name,type,test_way,normal_weight,end_weight);
}
void deal_3(String name, String type, String test_way,String normal_weight, String end_weight)
{
if(!courses.containsKey(name)) {
courses.put(name, new Test_Course(name, type, test_way,normal_weight, end_weight));
}
}
void setLabCourses(String name, String type, String test_way,String line){
deal_4(name,type,test_way,line);
}
void deal_4(String name, String type, String test_way,String line)
{
if(!courses.containsKey(name)) {
courses.put(name, new labcor(name, type, test_way,line));
}
}
private static void sortAndPrintByDate1(String[] idArray) {
Arrays.sort(idArray, (id1, id2) -> {
// 提取年月日部分进行比较
String date1 = id1.substring(6, 10) + "-" + id1.substring(10, 12) + "-" + id1.substring(12, 14);
String date2 = id2.substring(6, 10) + "-" + id2.substring(10, 12) + "-" + id2.substring(12, 14);
return date1.compareTo(date2);
});
Arrays.stream(idArray).forEach(id->{
System.out.println(id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14));
});
}
void setClasses(String num){
deal_5(num);
}
void deal_5(String num)
{
if(!classes.containsKey(num)) {
classes.put(num, new Class(num));
}
}
void setStudents(String clas_num, String name, String num){//班级号 姓名 学号
deal_6(clas_num,name,num);
}
void deal_6(String clas_num, String name, String num){
if(classes.containsKey(clas_num)){
if(!classes.get(clas_num).students.containsKey(num))
classes.get(clas_num).students.put(num,new Student(name,num));
}
}
void setStu__st_courAndMap(String num,String course,String normal_score,String end_score){//添加选课类 学生姓名 课程名称 分数
deal_7(num,course,normal_score,end_score);
}
void deal_7(String num,String course,String normal_score,String end_score)
{
if(!stu__st_cour.containsKey(num)){
stu__st_cour.put(num,new StudentsAll_mes(num,course,normal_score,end_score));
}
else{
stu__st_cour.get(num).setGradeMap(course,normal_score,end_score);
}
}
void setStu__st_courAndMap(String num,String course,String end_score){
deal_8(num,course,end_score);
}
void deal_8(String num,String course,String end_score)
{
if(!stu__st_cour.containsKey(num)){
stu__st_cour.put(num,new StudentsAll_mes(num,course,end_score));
}
else{
stu__st_cour.get(num).setGradeMap(course,end_score);
}
}
void set_lab_grades(String stu_num,String course,String lab_num,String grades){
deal_9(stu_num,course,lab_num,grades);
}
void deal_9(String stu_num,String course,String lab_num,String grades)
{
ArrayList<Integer> scores = new ArrayList<>();
String[] tem = grades.split(" ");
for(int i=3;i<tem.length;i++){
if(tem[i].matches("\\d+"))
scores.add(Integer.parseInt(tem[i]));
}
if(!stu__st_cour.containsKey(stu_num)){
StudentsAll_mes tem_stu_mes = new StudentsAll_mes();
tem_stu_mes.set_lab_stu_mes(stu_num,course,lab_num,scores);
stu__st_cour.put(stu_num,tem_stu_mes);
}else{
stu__st_cour.get(stu_num).set_lab_gmap(course,lab_num,scores);
}
}
}
class Input_Format {
String regex_c_test = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修)\\s考试\\s((0.\\d{1,2})|(1-9?))\\s((0.\\d{1,2})|(1-9?))$";
String regex_c_inspect = "[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s选修\\s考察$";
String regex_c_lab = "^[\\u4e00-\\u9fa5a-zA-Z0-9 ]{1,10}\\s实验\\s实验\\s[4-9]\\s((0.\\d{1,2})|(1-9?))(\\s((0.\\d{1,2})|(1-9?))){3,9}$";
String regex_CS = "^\\d{8}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s+[\\u4E00-\\u9FA5A-Za-z0-9]{1,10}\\s*((100)|(\\d{1,2})|(0))?\\s+((100)|(\\d{1,2})|(0))$";
String regex_lab = "^\\d{8}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s[\\u4e00-\\u9fa5a-zA-Z0-9 ]{1,10}\\s((100)|([1-9]\\d)|\\d)(\\s((100)|([1-9]\\d)|\\d)){2,9}$";
boolean isEnd = true;//结束标志
String[] strings;
void inpross(String line,afwefr del_sto) {
deal_1(line,del_sto);
}
void deal_1(String line,afwefr del_sto)
{
lineProcessing(line);//分割
del_sto.output.add_input(line);//存储
if(line.matches(regex_c_inspect)){
del_sto.setInspectCourses(strings[0],strings[1],strings[2]);
}else if(line.matches(regex_c_lab)){
del_sto.setLabCourses(strings[0],strings[1],strings[2],line);
}else if(line.matches(regex_c_test)){
del_sto.setTestCourses(strings[0],strings[1],strings[2],strings[3],strings[4]);//成绩信息
} else if(line.matches(regex_CS)||line.matches(regex_lab)){
del_sto.setClasses(strings[0].substring(0,6));
del_sto.setStudents(strings[0].substring(0, 6), strings[1], strings[0]);//学生的添加
if (del_sto.courses.containsKey(strings[2])) {//课程里有这个课
if (del_sto.courses.get(strings[2]).type.equals("选修")) {//
if (del_sto.courses.get(strings[2]).test_way.equals("考试")&&strings.length == 5) {
del_sto.setStu__st_courAndMap(strings[0], strings[2], strings[3], strings[4]);
}else if(del_sto.courses.get(strings[2]).test_way.equals("考察")&&strings.length==4){
del_sto.setStu__st_courAndMap(strings[0], strings[2], strings[3]);
} else {
del_sto.setStu__st_courAndMap(strings[0], strings[2], "no access", "no access");
}
} else if (del_sto.courses.get(strings[2]).type.equals("必修")) {//
if (strings.length == 5) {
del_sto.setStu__st_courAndMap(strings[0], strings[2], strings[3],strings[4]);
} else {//无效
del_sto.setStu__st_courAndMap(strings[0], strings[2], "no access", "no access");
}
} else if(del_sto.courses.get(strings[2]).type.equals("实验")){
if(strings.length == 3+((labcor) del_sto.courses.get(strings[2])).asscorenum){
del_sto.set_lab_grades(strings[0],strings[2], String.valueOf(((labcor) del_sto.courses.get(strings[2])).asscorenum),line);
}else{
del_sto.set_lab_grades(strings[0],strings[2],"num error","no access");
}
}
}else{
del_sto.setStu__st_courAndMap(strings[0], strings[2], "not exist");
}
}
}
void lineProcessing(String line){
strings = line.split(" ");
}
}
class Inspect_Score extends Score{
String end_score;
Inspect_Score(String end_score) {
this.end_score = end_score;
}
}
class Output_Format {
cal_grade calculate = new cal_grade();
String regex_c_test = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s((\\d{1,2})|(1-9?))\\s((\\d{1,2})|(1-9?))$";
String regex_c_test_e = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s((0.\\d{1,2})|(1-9?))\\s((0.\\d{1,2})|(1-9?))$";
String regex_c_inspect = "[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)$";
String regex_c_lab = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s[4-9]\\s((0.\\d{1,2})|(1-9?))(\\s((0.\\d{1,2})|(1-9?))){1,10}$";
String regex_CS = "^\\d{8}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s*((100)|(\\d{1,2})|(0))?\\s+((100)|(\\d{1,2})|(0))$";
String regex_lab = "^\\d{8}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s((100)|([1-9]\\d)|\\d)(\\s((100)|([1-9]\\d)|\\d)){1,20}$";
String name1;
String name2;
String grade1;
String grade2;
String name3;
Output_Format() {name1 = "hello";name2 = "hello";grade1 = "hello";grade2 = "hello";name3 = "hello";}
String get_name1() {return name1;}
String get_name2() {return name2;}
String get_name3() {return name3;}
void outputProcessing(afwefr data) {
deal_4(data);
}
void output_all(afwefr data){
data.output.output.forEach(System.out::println);
}
void deal_4(afwefr data)
{
data.classes.forEach((num,Class)-> Class.students.forEach((name, student)-> calculate.final_score(data,student.num)));
for(String i:data.output.input){
String[] tem = i.split(" ");
if(i.matches(regex_c_test_e)||i.matches(regex_c_test)||i.matches(regex_c_inspect)||i.matches(regex_c_lab)){
if(tem[1].equals("必修")&&(tem[2].equals("考察")||tem[2].equals("实验"))){
data.output.add_output(tem[0] + " : course type & access mode mismatch");
}else if(tem[1].equals("实验")&&!tem[2].equals("实验")) {
data.output.add_output(tem[0] + " : course type & access mode mismatch");
}else if(tem[1].equals("选修")&&tem[2].equals("实验")) {
data.output.add_output(tem[0] + " : course type & access mode mismatch");
}
if(tem[1].equals("实验")&&tem[2].equals("实验")) {
if(tem.length-4>=4&&tem.length - 4<=9) {
if (Integer.parseInt(tem[3]) != tem.length - 4) {
data.output.add_output(tem[0] + " : number of scores does not match");
data.courses.remove(tem[0]);
continue;
}
float tem_weight = 0;
for (int j = 4; j < tem.length; j++) {
tem_weight += Float.parseFloat(tem[j]);
}
if (Math.abs(tem_weight - 1) > 0.0001) {
data.output.add_output(tem[0] + " : weight value error");
data.courses.remove(tem[0]);
continue;
}
}else{
try {
if (Integer.parseInt(tem[3]) != tem.length - 4) {
data.output.add_output(tem[0] + " : number of scores does not match");
data.courses.remove(tem[0]);
continue;
}
} catch (Exception ignored) {
}
}
}if((tem[1].equals("必修")||tem[1].equals("选修"))&&tem[2].equals("考试")){
if(tem.length-3==2) {
float tem_weight = Float.parseFloat(tem[3]) + Float.parseFloat(tem[4]);
if (Math.abs(tem_weight - 1) > 0.0001) {
data.output.add_output(tem[0] + " : weight value error");
data.courses.remove(tem[0]);
}
}
}
}else if(i.matches(regex_CS)||i.matches(regex_lab)) {
if(!data.courses.containsKey(tem[2])){//不存在
data.output.add_output(tem[2]+" does not exist");
data.stu__st_cour.get(tem[0]).gmap.remove(tem[2]);
}else{
if(data.courses.get(tem[2]).type.equals("必修") && tem.length!=5) {//必修 但是只有期末成绩
data.output.add_output(tem[0]+" "+tem[1]+" : access mode mismatch");
}else if(data.courses.get(tem[2]).type.equals("选修")) {
if ((data.courses.get(tem[2]).test_way.equals("考试") && tem.length != 5) ||
(data.courses.get(tem[2]).test_way.equals("考察") && tem.length != 4))
data.output.add_output(tem[0] + " " + tem[1] + " : access mode mismatch");
}else if(data.courses.get(tem[2]).type.equals("实验")){
if(data.courses.get(tem[2]).test_way.equals("实验")&&(tem.length-3<4||tem.length-3>9||tem.length-3!=((labcor) data.courses.get(tem[2])).asscorenum))
data.output.add_output(tem[0] + " " + tem[1] + " : access mode mismatch");
}
}
}else if(!i.equals("end")){
data.output.add_output("wrong format");
}
}
data.classes.forEach((cla_num,Class1)->{//遍历所有班级
Class1.students.forEach((stu_num,student)->{
int tem=calculate.stagar(data,stu_num);
if(tem>=0)
data.output.add_output(stu_num+" "+Class1.students.get(stu_num).name+" "+tem);
else
data.output.add_output(stu_num+" "+Class1.students.get(stu_num).name+" "+"did not take any exams");
});
});
data.courses.forEach((key,value)-> {
int[] tem = calculate.scfrade(data, key);
if (tem[0] < 0 && tem[1] < 0 && tem[2] < 0) {//三个为- 则没成绩
data.output.add_output(key + " has no grades yet");
}else {
if (value.type.equals("选修") || value.type.equals("必修") || value.type.equals("实验")) {
data.output.add_output(key + " " + tem[2]);
}
}
});
data.classes.forEach((num,Class)->{
int tem = calculate.clas_grade(data,num);
if(tem>=0) {
data.output.add_output(num + " " + tem);
}else
data.output.add_output(num+" has no grades yet");
});
}
}
class Test_Score extends Score{
String normal_score;
String end_score;
Test_Score(String normal_score,String end_score) {
this.normal_score = normal_score;
this.end_score = end_score;
}
}
abstract class Score {
String total_scores = "-100";
}
class Student {
String name;
String num;
Student(String name, String num) {
this.name = name;
this.num = num;
}
}
class StudentsAll_mes {
String num;//学生
TreeMap<String,Score> gmap =new TreeMap<>();
StudentsAll_mes(String stu_name, String course, String normal_score,String test_score){
deal_1(stu_name,course,normal_score,test_score);
}
void deal_1(String stu_name, String course, String normal_score,String test_score)
{
this.num = stu_name;
gmap.put(course,new Test_Score(normal_score,test_score));
}
StudentsAll_mes(String stu_name, String course, String test_score){
deal_2(stu_name,course,test_score);
}
void deal_2(String stu_name, String course, String test_score)
{
this.num = stu_name;
gmap.put(course,new Inspect_Score(test_score));
}
StudentsAll_mes() {
}
void set_lab_stu_mes(String stu_num,String course,String lab_num,ArrayList<Integer> scores){
deal_3(stu_num,course,lab_num,scores);
}
void deal_3(String stu_num,String course,String lab_num,ArrayList<Integer> scores)
{
this.num = stu_num;
gmap.put(course,new Lab_Score(lab_num,scores));
}
void set_lab_gmap(String course,String lab_num,ArrayList<Integer> scores){
if(!gmap.containsKey(course))
gmap.put(course,new Lab_Score(lab_num,scores));
}
void setGradeMap(String course, String normal_score,String test_score){
if(!gmap.containsKey(course))
gmap.put(course, new Test_Score(normal_score,test_score));
}
void setGradeMap(String course,String test_score){
if(!gmap.containsKey(course))
gmap.put(course,new Inspect_Score(test_score));
}
}
class InAndOut_put {
List<String> output = new ArrayList<>();
List<String> input = new ArrayList<>();
void add_output(String out) {output.add(out);}void add_input(String out) {input.add(out);}
}
class Lab_Score extends Score {
String lab_num;//试验次数
ArrayList<Integer> scores;
Lab_Score(String lab_num,ArrayList<Integer> scores){
this.lab_num = lab_num;
this.scores = scores;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Input_Format inputFormat = new Input_Format();//输入
Output_Format outputFormat = new Output_Format();//输出
afwefr del_sto = new afwefr();
while (inputFormat.isEnd){
String inputLine = scanner.nextLine();
if(inputLine.equals("end")){
inputFormat.isEnd = false;
break;
}
inputFormat.inpross(inputLine,del_sto);
}
outputFormat.outputProcessing(del_sto);
outputFormat.output_all(del_sto);
}
}
类图:
1.2.4 期末考试
7-1 立体图形问题
代码
import javax.swing.undo.CannotUndoException;
import java.util.Arrays;
import java.util.Scanner;
import java.text.DecimalFormat;
class shape
{
double side;
double s;
double v;
public void cal_s()
{
}
public void cal_v()
{
}
}
class Cube extends shape
{
Cube(double s)
{
side = s;
}
@Override
public void cal_s() {
s = 6 * Math.pow(side, 2);
String formattedNumber = String.format("%.2f", s);
System.out.println(formattedNumber);
}
@Override
public void cal_v() {
v = Math.pow(side, 3);
String formattedNumber = String.format("%.2f", v);
System.out.println(formattedNumber);
}
}
class RegularPyramid extends shape
{
double h;
RegularPyramid(double s)
{
side = s;
h = Math.sqrt(2) / 3 * side;
}
@Override
public void cal_s() {
double baseArea = (Math.sqrt(3) / 4) * side * side;
double lateralArea = 3 * baseArea; // 正三棱锥有三个等边三角形的侧面
s = baseArea + lateralArea;
String formattedNumber = String.format("%.2f", s);
System.out.println(formattedNumber);
}
@Override
public void cal_v() {
v = (Math.sqrt(2) / 12) * side * side * side ;
String formattedNumber = String.format("%.2f", v);
System.out.println(formattedNumber);
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double side = input.nextDouble();
display(new Cube(side));
display(new RegularPyramid(side));
}
public static void display(shape p)
{
p.cal_s();
p.cal_v();
}
}
7-2 魔方问题
利用“立体图形”问题源码,实现如下功能:
魔方有三个属性:颜色,阶数,类型(正方体魔方、正三棱锥魔方),程序要求输出魔方的颜色、表面积和体积。参考设计类图如下所示:
代码:
import javax.swing.undo.CannotUndoException;
import java.util.Arrays;
import java.util.Scanner;
import java.text.DecimalFormat;
class shape
{
String color;
int layer;
double side;
double s;
double v;
public void print_color()
{
}
public void print_layer()
{
}
public void cal_s()
{
}
public void cal_v()
{
}
}
class Cube extends shape
{
Cube(String color,int layer,double s)
{
this.color = color;
this.layer = layer;
this.side = s * layer;
}
public void print_color()
{
System.out.println(this.color);
}
public void print_layer()
{
System.out.println(this.layer);
} @Override
public void cal_s() {
s = 6 * Math.pow(side, 2);
String formattedNumber = String.format("%.2f", s);
System.out.println(formattedNumber);
}
@Override
public void cal_v() {
v = Math.pow(side, 3);
String formattedNumber = String.format("%.2f", v);
System.out.println(formattedNumber);
}
}
class RegularPyramid extends shape
{
RegularPyramid(String color,int layer,double s)
{
this.color = color;
this.layer = layer;
this.side = s * layer;
}
public void print_color()
{
System.out.println(this.color);
}
public void print_layer()
{
System.out.println(this.layer);
}
@Override
public void cal_s() {
double baseArea = (Math.sqrt(3) / 4) * side * side;
double lateralArea = 3 * baseArea; // 正三棱锥有三个等边三角形的侧面
s = baseArea + lateralArea;
String formattedNumber = String.format("%.2f", s);
System.out.println(formattedNumber);
}
@Override
public void cal_v() {
v = (Math.sqrt(2) / 12) * side * side * side ;
String formattedNumber = String.format("%.2f", v);
System.out.println(formattedNumber);
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String color = input.next();
int layer = input.nextInt();
double side = input.nextDouble();
Cube a = new Cube(color,layer,side);
color = input.next();
layer = input.nextInt();
side = input.nextDouble();
RegularPyramid b = new RegularPyramid(color, layer,side);
display(a);
display(b);
}
public static void display(shape p)
{
p.print_color();
p.cal_s();
p.cal_v();
}
}
7-3 魔方排序问题
在魔方问题的基础上,重构类设计,实现列表内魔方的排序功能(按照魔方的体积进行排序)。
代码:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Comparator;
abstract class afda{
double s;
abstract double gear();
abstract double afag();
}
class Cube extends afda {
private double s;
public Cube(double s) {
this.s = s;
}
@Override
public double gear() {
return 6 * s * s;
}
@Override
public double afag() {
return s * s * s;
}
}
class SquareCube extends RubikCube {
public SquareCube(String color, int layer, afda solid) {
super(color, layer, solid);
}
@Override
public double gear() {
return layer * layer * solid.gear();
}
@Override
public double afag() {
return layer * layer * layer * solid.afag();
}
}
class RegularPyramid extends afda {
private double s;
public RegularPyramid(double s) {
this.s = s;
}
@Override
public double gear() {
double baseArea = (Math.sqrt(3) / 4) * s * s;
double lateralArea = 3 * baseArea; // 正三棱锥有三个等边三角形的侧面
return baseArea + lateralArea;
}
@Override
public double afag() {
return (Math.sqrt(2) / 12) * s * s * s ;
}
}
class RegularPyramidCube extends RubikCube {
public RegularPyramidCube(String color, int layer, afda solid) {
super(color, layer, solid);
}
@Override
public double gear() {
return layer * layer * solid.gear();
}
@Override
public double afag() {
return layer * layer*layer * solid.afag();
}
}
abstract class RubikCube implements Comparable<RubikCube> {
String color;
int layer;
afda solid;
public RubikCube(String color, int layer, afda solid) {
this.color = color;
this.layer = layer;
this.solid = solid;
}
public String getColor() {
return color;
}
public int getLayer() {
return layer;
}
public abstract double gear() ;
public abstract double afag() ;
@Override
public int compareTo(RubikCube other) {
// Compare RubikCubes based on their volumes
return Double.compare(this.afag(), other.afag());
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String color;
int layer;
double s;
RubikCube cube;
ArrayList<RubikCube> list = new ArrayList<>();
int choice = input.nextInt();
while (choice != 0) {
switch (choice) {
case 1:// SquareCube
color = input.next();
layer = input.nextInt();
s = input.nextDouble();
cube = new SquareCube(color, layer, new Cube(s));
list.add(cube);
break;
case 2:// RegularPyramidCube
color = input.next();
layer = input.nextInt();
s = input.nextDouble();
cube = new RegularPyramidCube(color, layer, new RegularPyramid(s));
list.add(cube);
break;
}
choice = input.nextInt();
}
list.sort(Comparator.naturalOrder());// 正向排序
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getColor() + " " +
String.format("%.2f", list.get(i).gear()) + " " +
String.format("%.2f", list.get(i).afag()));
System.out.println("");
}
}
}
1.3 总结
我学到了很多关于代码改进的知识和技巧。我意识到了面向对象的设计和合适的数据结构对于代码的可读性和可维护性的重要性。我也学会了使用流式操作和Lambda表达式来简化代码。此外,我还学到了错误处理和异常处理的重要性,以及如何编写适当的单元测试来验证代码的正确性。
然而,我也意识到自己还有很多需要进一步学习和研究的地方。首先,我需要进一步学习和掌握更多的面向对象的设计原则和模式,以便更好地设计和实现代码。其次,我需要深入了解不同的数据结构和算法,并了解它们的优缺点,以便在实际的编程中能够选择合适的数据结构和算法。此外,我还需要进一步学习和研究关于异常处理和错误处理的最佳实践,以及如何编写更全面和有效的单元测试。
标签:tem,String,int,BLOG3,num,void,name From: https://www.cnblogs.com/swc2003/p/17891128.html