pta第一次大作业-卢文博
第一次大作业
7-1设计一个风扇Fan类
主要代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fan fan1 = new Fan();
System.out.println("-------");
System.out.println("Default");
System.out.println("-------");
System.out.println(fan1);
int speed = in.nextInt();
boolean on = "True".equals(in.next());
double radius = in.nextDouble();
String color = in.next();
Fan fan2 = new Fan(speed,on,radius,color);
System.out.println("-------");
System.out.println("My Fan");
System.out.println("-------");
System.out.println(fan2);
}
}
class Fan{
private final int SLOW = 1;
private final int MEDIUM = 2;
private final int FAST = 3;
private int speed = SLOW;
private boolean on = false;
private double radius = 5;
private String color = "white";
public Fan(int speed, boolean on, double radius, String color) {
this.speed = speed;
this.on = on;
this.radius = radius;
this.color = color;
}
public Fan() {
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
@Override
public String toString() {
if(on){
return "speed "+speed+"\ncolor "+color+"\nradius "+radius+"\nfan is on";
}else{
return "speed "+speed+"\ncolor "+color+"\nradius "+radius+"\nfan is off";
}
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
这个fan类主要考察了:
类和对象的基本概念
构造方法的使用
变量的封装(使用私有数据域和访问器、修改器)
方法重写(toString方法)
条件语句和用户输入处理
7-2类和对象的使用
我认为这个题题目和上面fan类比较类似
下面是student类的代码
class Student{
private String name;
private String sex;
private String ID;
private int age;
private String major;
public Student(){};
public Student(String name,String sex,String ID,int age,String major){
this.name=name;
this.sex=sex;
this.ID=ID;
this.age=age;
this.major=major;
}
public void set(){
}
public String getname(String name){
return this.name;
}
public String getsex(String sex){
return this.sex;
}
public String ID(String ID){
return this.ID;
}
public int age(int age){
return this.age;
}
public String major(String major){
return this.major;
}
public String toString(){
return "姓名:"+this.name+", 性别:"+this.sex+", 学号:"+this.ID+", 年龄:"+this.age+", 专业:"+this.major;}//获取学生所有属性的方法
public void printInfo(){
System.out.print("姓名:"+this.name);
System.out.print(",性别:"+this.sex);
System.out.print(",学号:"+this.ID);
System.out.print(",年龄:"+this.age);
System.out.print(",专业:"+this.major);
}
主要考察和fan类类似几个方面:
面向对象编程:理解类的属性和方法的使用。
封装:通过私有属性和公共 getter/setter 方法来保护数据。
构造器的使用:理解如何使用多种构造器来初始化对象。
输入输出操作:通过控制台输入输出学生信息。
方法重写:理解 toString() 方法的重写和使用。
7-3与7-4与上面两个相似都是一些简单的类的构造,就不作赘述了
7-5答题判题程序-1
这个题目是这次作业中最难的一道题目,也是以后几次作业要作更新迭代的程序,但题目有些难度
下面是我的部分代码
class Question {
String Number;
String content;
String StandardAnswer;
public String getNumber() {
return Number;
}
public Question(String Number, String content, String StandardAnswer) {
this.Number = Number;
this.content = content;
this.StandardAnswer = StandardAnswer;
}
public void setNumber(String Number) {
this.Number = Number;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getStandardAnswer() {
return StandardAnswer;
}
public void setStandardAnswer(String StandardAnswer) {
this.StandardAnswer = StandardAnswer;
}
在我构造的类中
Main 类负责读取输入、处理数据并输出结果。
Question 类封装了问题的编号、内容和标准答案,提供了相应的 getter 和 setter 方法。
在代码中用到了一些正则表达式例如
分割输入字符串:
String[] parts = input[i].split("#N:|#A:|#Q:");
这里的 split 方法使用了正则表达式 #N:|#A:|#Q:,表示将输入字符串根据 #N:, #A: 和 #Q: 这三个标记进行分割。
分割答案字符串:
String answer[] = ans.split("#A:");
这里的 split 方法同样使用了正则表达式 #A:,用于将答案字符串按 #A: 分割。
正则表达式允许灵活地匹配字符串模式,非常适合处理这类文本分割的需求,似的数据更便于处理。
并且因为自己对正则表达式的理解不够,出现了很多问题
第二次大作业
这次大作业共有四题与第一次差不多重点在最后一题
手机按价格排序、查找
这个题目要求该类实现Comparable接口,重写compareTo方法
实现 Comparable 接口使得类的对象能够被排序,是 Java 中一种非常强大的功能。它使得开发者可以简单地定义对象的自然顺序,便于进行排序、搜索等操作。
下面是代码的实现
import java.util.*;
import java.util.Scanner;
class MobilePhone implements Comparable<MobilePhone> {
private String type;
private int price;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<MobilePhone> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String type = sc.next();
int price = sc.nextInt();
MobilePhone mobilePhone = new MobilePhone(type, price);
list.add(mobilePhone);
}
System.out.println("排序前,链表中的数据:");
for (MobilePhone phone : list) {
System.out.println(phone);
}
Collections.sort(list);
System.out.println("排序后,链表中的数据:");
for (MobilePhone phone : list) {
System.out.println(phone);
}
String typeToFind = sc.next();
int priceToFind = sc.nextInt();
MobilePhone mobilePhoneToFind = new MobilePhone(typeToFind, priceToFind);
boolean found = false;
for (MobilePhone phone : list) {
if (phone.getPrice() == mobilePhoneToFind.getPrice()) {
found = true;
System.out.println(typeToFind + "与链表中的" + phone.getType() + "价格相同");
}
}
if (!found) {
System.out.println("链表中的对象,没有一个与" + typeToFind + "价格相同的");
}
}
}
- MobilePhone 类
class MobilePhone implements Comparable{
这个类实现了 Comparable 接口,允许对 MobilePhone 对象进行排序。
属性
private String type;
private int price;
type:手机的型号(类型)。
price:手机的价格。
构造函数
public MobilePhone(String type, int price) {
this.type = type;
this.price = price;
}
用于初始化 MobilePhone 对象的类型和价格。
Getter 和 Setter 方法
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public int getPrice() { return price; }
public void setPrice(int price) { this.price = price; }
提供获取和设置 type 和 price 的方法。
compareTo 方法
public int compareTo(MobilePhone other) {
return Integer.compare(this.price, other.price);
}
实现了价格的比较逻辑,使得可以根据价格对 MobilePhone 对象进行排序。
toString 方法
public String toString() {
return "型号:" + type + ",价格:" + price;
}
重写了 toString 方法,以便打印出手机的型号和价格。
sdut-oop-4-求圆的面积(类与对象)
第2题代码也作省略
主要讲一下我写的类的属性和方法
Circle 类:
包含一个私有成员变量 radius,表示圆的半径。
提供了无参构造方法和有参构造方法。
setRadius 方法用于设置半径值,若输入小于等于0,则设置为2。
getRadius 方法返回当前半径值。
getArea 方法用于计算圆的面积。
重写了 toString 方法以便于输出对象的字符串表示。
Main 类:
创建了 Circle 类的对象 c1 和 c2,并输出其信息和面积。
通过键盘输入接收整型半径并赋值给 c2。
再次接收整型半径,并使用有参构造方法创建第三个 Circle 对象 c3,输出其信息和面积。
答题判题程序-2
这一道题是第一次大作业最后一题的迭代题目
由于我第一次大作业的类的属性方法的构造思考方法不够全面以及正则表达式的运用不够熟练
这次题目只得到了一点分数
下面是我的代码
import java.util.Scanner;
class Question {
String id;
String content;
String answer;
public Question(String id, String content, String answer) {
this.id = id;
this.content = content;
this.answer = answer;
}
public String getId() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
class TestPaper {
String id;
Map<String, Integer> questions; // 题目ID和分值的映射
public TestPaper(String id) {
this.id = id;
this.questions = new HashMap<>();
}
public void addQuestion(String questionId, int score) {
questions.put(questionId, score);
}
public int getTotalScore() {
return questions.values().stream().mapToInt(Integer::intValue).sum();
}
}
class AnswerSheet {
String testPaperId;
List<String> answers;
public AnswerSheet(String testPaperId) {
this.testPaperId = testPaperId;
this.answers = new ArrayList<>();
}
public void addAnswer(String answer) {
answers.add(answer);
}
}
public class Main {
private static final List<Question> questions = new ArrayList<>();
private static final List<TestPaper> testPapers = new ArrayList<>();
private static final List<AnswerSheet> answerSheets = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line;
// 读取输入
while (!(line = sc.nextLine()).equals("end")) {
processInput(line.trim());
}
sc.close();
// 处理输出
processOutput();
}
private static void processInput(String line) {
if (line.startsWith("#N:")) {
// 处理题目信息
String[] parts = line.split(" ");
String id = parts[0].substring(3);
String content = parts[1].substring(3);
String answer = parts[2].substring(3);
questions.add(new Question(id, content, answer));
} else if (line.startsWith("#T:")) {
// 处理试卷信息
String[] parts = line.split(" ");
String testPaperId = parts[0].substring(3);
TestPaper testPaper = new TestPaper(testPaperId);
for (int i = 1; i < parts.length; i++) {
String[] questionParts = parts[i].split("-");
String questionId = questionParts[0];
int score = Integer.parseInt(questionParts[1]);
testPaper.addQuestion(questionId, score);
}
testPapers.add(testPaper);
} else if (line.startsWith("#S:")) {
// 处理答卷信息
String[] parts = line.split(" ");
String testPaperId = parts[0].substring(3);
AnswerSheet answerSheet = new AnswerSheet(testPaperId);
for (int i = 1; i < parts.length; i++) {
String answer = parts[i].substring(3);
answerSheet.addAnswer(answer);
}
answerSheets.add(answerSheet);
}
}
}
下面是我写的代码几个类以及思路逻辑
- Question 类
属性:
String id: 题目的唯一标识符。
String content: 题目的内容。
String answer: 题目的正确答案。
方法:
Question(String id, String content, String answer): 构造函数,用于初始化题目。
getId(): 返回题目ID。
setID(String id): 设置题目ID。
getContent(): 返回题目内容。
setContent(String content): 设置题目内容。
getAnswer(): 返回答案。
setAnswer(String answer): 设置答案。 - TestPaper 类
属性:
String id: 试卷的唯一标识符。
Map<String, Integer> questions: 题目ID与分数的映射。
方法:
TestPaper(String id): 构造函数,用于初始化试卷。
addQuestion(String questionId, int score): 添加题目及其分数。
getTotalScore(): 计算并返回试卷的总分。 - AnswerSheet 类
属性:
String testPaperId: 关联的试卷ID。
Listanswers: 答案列表。
方法:
AnswerSheet(String testPaperId): 构造函数,用于初始化答卷。
addAnswer(String answer): 添加答案到答卷。
主类 Main
属性:
Listquestions: 存储所有题目的列表。
ListtestPapers: 存储所有试卷的列表。
ListanswerSheets: 存储所有答卷的列表。
方法:
main(String[] args): 程序的入口,处理输入和输出。
processInput(String line): 处理输入的每一行,根据前缀判断是题目、试卷还是答卷。
如果以 #N: 开头,解析题目信息并创建 Question 对象。
如果以 #T: 开头,解析试卷信息并创建 TestPaper 对象。
如果以 #S: 开头,解析答卷信息并创建 AnswerSheet 对象。
processOutput(): 处理输出,验证并输出每份答卷的结果。
遍历试卷,检查是否总分为100。
遍历答卷,校对答案,并输出每道题的结果和总分
但由于种种问题,以及我给的限制条件不够导致只有几个测试用例是正确的只得了12分
第三次大作业
这次大作业只有三道题目,仍然是最后一题为迭代更新的题目
面向对象编程(封装性)
这道题目主要考察类:封装成员变量的访问修饰符使用(private),以及如何通过公共方法(getter 和 setter)来访问和修改这些私有变量。
封装的概念,以及它如何提高代码的安全性和可维护性。
下面是我构造的两个类与方法
- Student 类
属性
sid:学生的学号(字符串类型)。
name:学生的姓名(字符串类型)。
age:学生的年龄(整型)。
major:学生的专业(字符串类型)。
构造方法
无参构造方法:提供一个默认的构造方法,允许创建 Student 对象而不初始化任何属性。
有参构造方法:接收 sid、name、age 和 major 作为参数,并初始化相应的属性。
对 age 属性进行合法性检查,确保其值大于0,如果不合法,则将其设置为0。
方法
print():打印学生的详细信息,包括学号、姓名、年龄和专业。
访问器(getter)和修改器(setter):
setSid() 和 getSid():设置和获取学号。
setName() 和 getName():设置和获取姓名。
setAge() 和 getAge():设置和获取年龄,setAge() 方法同样包含合法性检查。
setMajor() 和 getMajor():设置和获取专业。 - Main 类
main 方法
创建一个 Scanner 对象 sc,用于从标准输入读取数据。
使用 sc.next() 和 sc.nextInt() 方法分别读取学生的学号、姓名、年龄和专业。
创建第一个 Student 对象 student1:
使用无参构造方法,然后通过 setter 方法设置属性。
创建第二个 Student 对象 student2:
直接使用有参构造方法初始化属性。
打印学生信息
调用 student1.print() 和 student2.print(),打印两个学生的详细信息。
答题判题程序-3
这次的迭代由于前面两次的漏洞过于多导致这次的迭代我完成不了,
下面是我的代码仅供记录(没有任何作用)
import java.util.*;
public class QuizApp {
static class Question {
String content;
String answer;
boolean isDeleted;
public Question(String content, String answer) {
this.content = content;
this.answer = answer;
this.isDeleted = false;
}
}
static class Paper {
String id;
List<QuestionScore> questionScores;
int totalScore;
public Paper(String id) {
this.id = id;
this.questionScores = new ArrayList<>();
this.totalScore = 0;
}
}
static class QuestionScore {
String questionContent;
String studentAnswer;
boolean isCorrect;
int score;
public QuestionScore(String questionContent, String studentAnswer, boolean isCorrect, int score) {
this.questionContent = questionContent;
this.studentAnswer = studentAnswer;
this.isCorrect = isCorrect;
this.score = score;
}
}
static class Student {
String id;
String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
}
private static Map<String, Question> questions = new HashMap<>();
private static Map<String, List<Paper>> papers = new HashMap<>();
private static Map<String, Student> students = new HashMap<>();
private static Set<String> deletedQuestions = new HashSet<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
while (!(input = scanner.nextLine()).equals("end")) {
processInput(input);
}
outputResults();
}
private static void processInput(String input) {
String[] parts = input.split(" ");
if (input.startsWith("#N:")) {
// 处理题目信息
handleQuestion(parts);
} else if (input.startsWith("#T:")) {
// 处理试卷信息
handleTestPaper(parts);
} else if (input.startsWith("#X:")) {
// 处理学生信息
handleStudent(parts);
} else if (input.startsWith("#S:")) {
// 处理答卷信息
handleStudentAnswer(parts);
} else if (input.startsWith("#D:")) {
// 处理删除题目信息
handleDeleteQuestion(parts);
} else {
System.out.println("wrong format:" + input);
}
}
private static void handleQuestion(String[] parts) {
String questionId = parts[0].substring(3);
String questionContent = parts[1].substring(3);
String answer = parts[2].substring(3);
questions.put(questionId, new Question(questionContent, answer));
}
private static void handleTestPaper(String[] parts) {
String testId = parts[0].substring(3);
List<QuestionScore> questionScores = new ArrayList<>();
int totalScore = 0;
for (int i = 1; i < parts.length; i++) {
String[] questionInfo = parts[i].split("-");
String questionId = questionInfo[0];
int score = Integer.parseInt(questionInfo[1]);
totalScore += score;
questionScores.add(new QuestionScore(questions.get(questionId).content, "", false, score));
}
Paper paper = new Paper(testId);
paper.questionScores = questionScores;
paper.totalScore = totalScore;
papers.put(testId, paper);
}
private static void handleStudent(String[] parts) {
for (int i = 1; i < parts.length; i++) {
String[] studentInfo = parts[i].split("-");
String studentId = studentInfo[0];
String studentName = studentInfo[1];
students.put(studentId, new Student(studentId, studentName));
}
}
private static void handleStudentAnswer(String[] parts) {
String testId = parts[0].substring(3);
String studentId = parts[1];
String studentName = students.containsKey(studentId) ? students.get(studentId).name : null;
Paper paper = papers.get(testId);
if (paper == null) {
System.out.println("the test paper number does not exist");
return;
}
for (int i = 2; i < parts.length; i++) {
String[] answerInfo = parts[i].split("-");
int questionIndex = Integer.parseInt(answerInfo[0]) - 1;
String answer = answerInfo[1].trim();
QuestionScore questionScore = paper.questionScores.get(questionIndex);
if (questionScore.questionContent == null) {
System.out.println("non-existent question~" + answer);
} else if (deletedQuestions.contains(questionScore.questionContent)) {
System.out.println("the question " + questionIndex + " invalid~0");
} else {
questionScore.studentAnswer = answer;
questionScore.isCorrect = answer.equals(questions.get(questionIndex).answer);
}
}
int totalScore = 0;
for (QuestionScore qs : paper.questionScores) {
totalScore += qs.isCorrect ? qs.score : 0;
}
System.out.println(studentId + (studentName != null ? " " + studentName : " not found") + ": " + totalScore + "~" + totalScore);
}
private static void handleDeleteQuestion(String[] parts) {
String questionId = parts[0].substring(3);
deletedQuestions.add(questionId);
}
private static void outputResults() {
// 输出总分警示
for (Paper paper : papers.values()) {
if (paper.totalScore != 100) {
System.out.println("alert: full score of test paper" + paper.id + " is not 100 points");
}
}
// 输出每道题的结果
// 此部分的实现可以根据具体需求调整
}
}import java.util.*;
public class QuizApp {
static class Question {
String content;
String answer;
boolean isDeleted;
public Question(String content, String answer) {
this.content = content;
this.answer = answer;
this.isDeleted = false;
}
}
static class Paper {
String id;
List<QuestionScore> questionScores;
int totalScore;
public Paper(String id) {
this.id = id;
this.questionScores = new ArrayList<>();
this.totalScore = 0;
}
}
static class QuestionScore {
String questionContent;
String studentAnswer;
boolean isCorrect;
int score;
public QuestionScore(String questionContent, String studentAnswer, boolean isCorrect, int score) {
this.questionContent = questionContent;
this.studentAnswer = studentAnswer;
this.isCorrect = isCorrect;
this.score = score;
}
}
static class Student {
String id;
String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
}
private static Map<String, Question> questions = new HashMap<>();
private static Map<String, List<Paper>> papers = new HashMap<>();
private static Map<String, Student> students = new HashMap<>();
private static Set<String> deletedQuestions = new HashSet<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
while (!(input = scanner.nextLine()).equals("end")) {
processInput(input);
}
outputResults();
}
private static void processInput(String input) {
String[] parts = input.split(" ");
if (input.startsWith("#N:")) {
// 处理题目信息
handleQuestion(parts);
} else if (input.startsWith("#T:")) {
// 处理试卷信息
handleTestPaper(parts);
} else if (input.startsWith("#X:")) {
// 处理学生信息
handleStudent(parts);
} else if (input.startsWith("#S:")) {
// 处理答卷信息
handleStudentAnswer(parts);
} else if (input.startsWith("#D:")) {
// 处理删除题目信息
handleDeleteQuestion(parts);
} else {
System.out.println("wrong format:" + input);
}
}
private static void handleQuestion(String[] parts) {
String questionId = parts[0].substring(3);
String questionContent = parts[1].substring(3);
String answer = parts[2].substring(3);
questions.put(questionId, new Question(questionContent, answer));
}
private static void handleTestPaper(String[] parts) {
String testId = parts[0].substring(3);
List<QuestionScore> questionScores = new ArrayList<>();
int totalScore = 0;
for (int i = 1; i < parts.length; i++) {
String[] questionInfo = parts[i].split("-");
String questionId = questionInfo[0];
int score = Integer.parseInt(questionInfo[1]);
totalScore += score;
questionScores.add(new QuestionScore(questions.get(questionId).content, "", false, score));
}
Paper paper = new Paper(testId);
paper.questionScores = questionScores;
paper.totalScore = totalScore;
papers.put(testId, paper);
}
private static void handleStudent(String[] parts) {
for (int i = 1; i < parts.length; i++) {
String[] studentInfo = parts[i].split("-");
String studentId = studentInfo[0];
String studentName = studentInfo[1];
students.put(studentId, new Student(studentId, studentName));
}
}
private static void handleStudentAnswer(String[] parts) {
String testId = parts[0].substring(3);
String studentId = parts[1];
String studentName = students.containsKey(studentId) ? students.get(studentId).name : null;
Paper paper = papers.get(testId);
if (paper == null) {
System.out.println("the test paper number does not exist");
return;
}
for (int i = 2; i < parts.length; i++) {
String[] answerInfo = parts[i].split("-");
int questionIndex = Integer.parseInt(answerInfo[0]) - 1;
String answer = answerInfo[1].trim();
QuestionScore questionScore = paper.questionScores.get(questionIndex);
if (questionScore.questionContent == null) {
System.out.println("non-existent question~" + answer);
} else if (deletedQuestions.contains(questionScore.questionContent)) {
System.out.println("the question " + questionIndex + " invalid~0");
} else {
questionScore.studentAnswer = answer;
questionScore.isCorrect = answer.equals(questions.get(questionIndex).answer);
}
}
int totalScore = 0;
for (QuestionScore qs : paper.questionScores) {
totalScore += qs.isCorrect ? qs.score : 0;
}
System.out.println(studentId + (studentName != null ? " " + studentName : " not found") + ": " + totalScore + "~" + totalScore);
}
private static void handleDeleteQuestion(String[] parts) {
String questionId = parts[0].substring(3);
deletedQuestions.add(questionId);
}
private static void outputResults() {
// 输出总分警示
for (Paper paper : papers.values()) {
if (paper.totalScore != 100) {
System.out.println("alert: full score of test paper" + paper.id + " is not 100 points");
}
}
}
}
下面是上面这段代码原本的思路
类定义:
Question类表示测验中的题目,包括内容、答案和删除状态。
Paper类表示试卷,包含试卷ID、题目分数列表和总分。
QuestionScore类存储每道题目的分数及学生回答的情况。
Student类包含学生的ID和姓名。
数据存储:
程序使用三个主要的数据结构:
questions: 保存所有题目,键为题目ID。
papers: 保存所有试卷,键为试卷ID。
students: 保存所有学生,键为学生ID。
deletedQuestions: 存储被标记为删除的题目的ID。
输入处理:
程序通过控制台读取输入(以字符串形式),根据不同的前缀(如#N:、#T:、#X:、#S:和#D:)调用不同的处理函数,添加题目、试卷、学生或处理学生提交的答案。
输出结果:
程序在输入结束后检查每个试卷的总分是否为100,并输出警告信息。
因为我的数据的结构不够完整,答案比较的逻辑错误以及handleStudentAnswer方法中的逻辑错误等等问题导致这次的题目没有完成
总结
正则表达式在处理和解析复杂的文本输入时有很大的优势,是一种高效、灵活且功能强大的工具。数据结构设计要合理,写这种复杂的程序,切记不可看完题目直接来敲代码,设计思路是重中之重,通过合理的设计可以在写代码是少走很多弯路。