Blog-3
作者:互联网
前言
这几周的作业所涉及的知识点有数据的封装和、继承与多态、正则表达式,还有抽象类和接口,另外还有javafx的一些基本知识。题量适中,但是难度对于我来说是比较大的。总的来说就是跟以前的题目差不多,只是题目类型有所改变——从之前的看题目写代码变成了看类图补全代码。
设计与分析
一、电信计费系列
1、 实现一个简单的电信计费程序:
假设南昌市电信分公司针对市内座机用户采用的计费方式:
月租20元,接电话免费,市内拨打电话0.1元/分钟,省内长途0.3元/分钟,国内长途拨打0.6元/分钟。不足一分钟按一分钟计。
南昌市的区号:0791,江西省内各地市区号包括:0790~0799以及0701。
2、实现南昌市电信分公司的计费程序,假设该公司针对手机和座机用户分别采取了两种计费方案,分别如下:
1、针对市内座机用户采用的计费方式(与电信计费系列1内容相同):
月租20元,接电话免费,市内拨打电话0.1元/分钟,省内长途0.3元/分钟,国内长途拨打0.6元/分钟。不足一分钟按一分钟计。
假设本市的区号:0791,江西省内各地市区号包括:0790~0799以及0701。
2、针对手机用户采用实时计费方式:
月租15元,市内省内接电话均免费,市内拨打市内电话0.1元/分钟,市内拨打省内电话0.2元/分钟,市内拨打省外电话0.3元/分钟,省内漫游打电话0.3元/分钟,省外漫游接听0.3 元/分钟,省外漫游拨打0.6元/分钟;
注:被叫电话属于市内、省内还是国内由被叫电话的接听地点区号决定,比如以下案例中,南昌市手机用户13307912264在区号为020的广州接听了电话,主叫号码应被计算为拨 打了一个省外长途,同时,手机用户13307912264也要被计算省外接听漫游费:
3、实现一个简单的电信计费程序,针对手机的短信采用如下计费方式:
1、接收短信免费,发送短信0.1元/条,超过3条0.2元/条,超过5条0.3元/条。
2、如果一次发送短信的字符数量超过10个,按每10个字符一条短信进行计算。
解释分析
我将三次电信计费的作业集合在一起,对于这道题,我在第一次是不知道怎么下手,即使它给了我几乎所有的类图,但是三个类图是分开来的,所以我都不知道怎么把这几个类图给联系起来,不过好在第二次我已经渐渐地知道了怎么写,并且把之前第一次的没写的补了上来。虽然测试点没有全过,但是还是很庆幸自己能一点点进步。这三道题是给类图然后写代码,所以在写之前我们要知道每一个类图想要表达什么意思和作用,我是现在编程软件上先把那些给定的类都提前敲好,然后再补充。其中的数据大多为字符串类型,所以我们在判断数据的过程中好多次都要用到正则表达式,这其实也是一个难点。另外在编程时要条例清晰,明白每一种计费方式的条件和价钱。
类图
代码如下
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); HashSet <String> u = new HashSet<>(); ArrayList <String>use = new ArrayList<>(); ArrayList <String>data = new ArrayList<>(); ArrayList<User> user = new ArrayList<>(); ArrayList <String>record= new ArrayList<>(); String input = in.nextLine(); while(!input.equals("end")) { if(input.contains(" ")) { if(input.length()>=15&&input.contains("u-")) { u.add(input); } else if(input.length()>=26) { data.add(input); } } input = in.nextLine(); } for(String a:u) { use.add(a); } Collections.sort(use); for(String a:use) { if(deal1(a)==1) { //System.out.println(data); for(String b:data) { if(deal2(a,b)==1) { //System.out.println("yes"); record.add(b); } } user.add(new User(a,record)); record.clear(); } } output(user); } private static void output(ArrayList<User> user) { for(User a:user) { System.out.print(a.getNumber()+" "); String cost = String.format("%.1f",a.calCost() ); System.out.print(cost+" "); System.out.print(a.calBalance()); System.out.println(""); } } private static int deal2(String a,String b) { String []n = a.split(" "); String []num = n[0].split("-"); String[]ab = b.split(" "); if(b.contains("t-")) { if(ab[0].contains(num[1])||ab[2].equals(num[1])||ab[1].equals(num[1])) { if(ab[1].matches("[0-9]{11,12}")&&ab[2].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[3].matches("([0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]") &&ab[4].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[5].matches("([0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]")) { return 1; } // u-13811111111 1 // t-13811111111 0791 13811111110 020 2022.1.3 08:00:00 2022.1.3 08:09:20 // end else if(ab[1].matches("[0-9]{3,4}")&&ab[2].matches("1[0-9]{10}")&&ab[3].matches("[0-9]{3,4}") &&ab[4].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[5].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]") &&ab[6].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[7].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]")) { return 1; } //t-13986300001 0791 079186300001 2022.12.31 23:50:25 2023.1.2 00:05:11 else if(ab[1].matches("[0-9]{3,4}")&&ab[2].matches("1[0-9]{10}")&&ab[3].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[4].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]") &&ab[5].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[6].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]")) { return 1; } else if(ab[1].matches("1[0-9]{10}")&&ab[2].matches("[0-9]{4}")&&ab[3].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[4].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]") &&ab[5].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[6].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]")) { return 1; } else if(ab[1].matches("[0-9]{3,4}")&&ab[2].matches("[0-9]{11,13}")&&ab[3].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[4].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]") &&ab[5].matches("[0-9]{4}\\.([1-9]|1[0-2])\\.([1-9]|[1-2][0-9]|3[0-1])") &&ab[6].matches("(0[0-9]|1[0-9]|2[0-3])\\:[0-5][0-9]\\:[0-5][0-9]")) { return 1; } } } else if(b.contains("m-")) { String[]bb = b.split(" "); if(bb.length>=3) { String ms = b.substring(26,b.length()); String regEx = "[_`~!@#$%^&*()+=|{}':;'\\[\\]<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t|[\u4e00-\u9fa5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(ms); if(ab[0].matches("m\\-[0-9]{11}")&&ab[1].matches("[0-9]{11}")) { while(m.find()) { return 0; } return 1; } } } return 0; } private static int deal1(String data) { String []data1 = data.split(" "); //u-13986300001 1 if(data1.length==2) { if(data1[0].matches("u-0791"+"[0-9]{7,9}$")) { return 1; } else if(data1[0].matches("u-1"+"[0-9]{9,11}$")) { return 1; } } return 0; } } class User{ private UserRecords userRecords = new UserRecords(); private double balance = 100; private ChargeMode chargeMode; private String number; private String choice; User(String use,ArrayList<String>record){ String []n = use.split(" "); this.choice = n[1]; String []num = n[0].split("-"); this.setNumber(num[1]); if(n[1].equals("0")||n[1].equals("1")) { for(String a:record) { CallRecord deal = new CallRecord(); deal.Deal(a,userRecords,choice,n); } } else { for(String a:record) { MessageRecord deal = new MessageRecord(); deal.Deal(a,userRecords,num[1]); } } if(n[1].equals("0")) { this.chargeMode = new LandlinePhoneCharging(); } else if(n[1].equals("1")) { this.chargeMode = new PhoneChaging(); } else if(n[1].equals("3")) { this.chargeMode = new MassageChaging(); } } //t-13986300001 0791 079186300001 2022.12.31 23:50:25 2023.1.1 00:05:11 public double calCost() { return chargeMode.calCost(this.userRecords); } public double calBalance() { return balance - chargeMode.getMonthlyRent()-chargeMode.calCost(userRecords); } public UserRecords getUserRecords() { return userRecords; } public void setUserRecords(UserRecords userRecords) { this.userRecords = userRecords; } public ChargeMode getChargeMode() { return chargeMode; } public void setChargeMode(ChargeMode chargeMode) { this.chargeMode = chargeMode; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } } class UserRecords{ private ArrayList<CallRecord> callingInCityRecords = new ArrayList<CallRecord>(); private ArrayList<CallRecord> callingInProvinceRecords = new ArrayList<CallRecord>(); private ArrayList<CallRecord> callingInLandRecords = new ArrayList<CallRecord>(); private ArrayList<CallRecord> answerInCityRecords = new ArrayList<CallRecord>(); private ArrayList<CallRecord> answerInProvinceRecords = new ArrayList<CallRecord>(); private ArrayList<CallRecord> answerInLandRecords = new ArrayList<CallRecord>(); private ArrayList<MessageRecord> sendMessageRecords = new ArrayList<MessageRecord>(); private ArrayList<MessageRecord> receiveMessageRecords = new ArrayList<MessageRecord>(); public void addCallingInCityRecords (CallRecord callRecord) { callingInCityRecords.add(callRecord); } public void addCallingInProvinceRecords (CallRecord callRecord) { callingInProvinceRecords.add(callRecord); } public void addCallingInLandRecords (CallRecord callRecord) { callingInLandRecords.add(callRecord); } public void addAnswerInCityRecords (CallRecord answerRecord) { answerInCityRecords.add(answerRecord); } public void addAnswerInProvinceRecords (CallRecord answerRecord) { answerInProvinceRecords.add(answerRecord); } public void addAnswerInLandRecords (CallRecord answerRecord) { answerInLandRecords.add(answerRecord); } public void addSendMessageRecords (MessageRecord sendMessageRecord) { sendMessageRecords.add(sendMessageRecord); } public void addReceiveMessageRecords (MessageRecord receiveMessageRecord) { receiveMessageRecords.add(receiveMessageRecord); } public ArrayList<MessageRecord> getSendMessageRecords (){ return sendMessageRecords; } public ArrayList<MessageRecord> getReceiveMessageRecords (){ return receiveMessageRecords; } public ArrayList<CallRecord> getCallingInCityRecords (){ return callingInCityRecords; } public ArrayList<CallRecord> getCallingInProvinceRecords (){ return callingInProvinceRecords; } public ArrayList<CallRecord> getCallingInLandRecords (){ return callingInLandRecords; } public ArrayList<CallRecord> getAnswerInCityRecords (){ return answerInCityRecords; } public ArrayList<CallRecord> getAnswerInProvinceRecords (){ return answerInProvinceRecords; } public ArrayList<CallRecord> getAnswerInLandRecords (){ return answerInLandRecords; } } class CallRecord extends CommunicationRecord{ private Date startTime; private Date endTime; private String callingAddressAreaCode; private String answerAddressAreaCode; public void Deal(String a, UserRecords userRecords,String choice,String[]n) { String []call = a.split(" "); String []num = call[0].split("-"); if(call.length==6) { if(call[1].length()==12) { this.setAnswerAddressAreaCode(call[1].substring(0,4)); } else { this.setAnswerAddressAreaCode(call[1].substring(0,3)); } this.setCallingAddressAreaCode(num[1].substring(0,4)); this.setCallingNumber(num[1]); this.setAnswerNumber(call[1]); } // 座机打手机: // t-主叫号码 接听号码 接听地点区号 起始时间 结束时间 // t-079186330022 13305862264 020 2022.1.3 10:00:25 2022.1.3 10:05:11 else if(call.length==7) { this.setAnswerAddressAreaCode(call[2]); this.setAnswerNumber(call[1]); this.setCallingAddressAreaCode(num[1].substring(0,4)); this.setCallingNumber(num[1]); } // 手机互打: // t-主叫号码 拨号地点 接听号码 接听地点区号 起始时间 结束时间 // t-18907910010 0791 13305862264 0371 2022.1.3 10:00:25 2022.1.3 10:05:11 else if(call.length==8) { this.setAnswerAddressAreaCode(call[3]); this.setAnswerNumber(call[2]); this.setCallingAddressAreaCode(call[1]); this.setCallingNumber(num[1]); } this.setTime(call); this.setType(userRecords,choice,call,num,n); } private void setTime(String []call) { int i = call.length-4; // t-079186330022 058686330022 2022.1.3 10:00:25 2022.1.3 10:05:11 SimpleDateFormat time = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); try { this.startTime = time.parse(call[i]+" "+call[i+1]); this.endTime = time.parse(call[i+2]+" "+call[i+3]); }catch (ParseException e) { } } private void setType(UserRecords userRecords,String choice,String[]call,String[]num,String []n) { if(choice.equals("0")) { String []nu= n[0].split("-"); if(this.getCallingNumber().equals(nu[1])) { if(this.getAnswerAddressAreaCode().matches("0791")) { userRecords.addCallingInCityRecords(this); } else if(this.getAnswerAddressAreaCode().matches("079[0-9]")|| this.getAnswerAddressAreaCode().matches("0701")) { userRecords.addCallingInProvinceRecords(this); } else { userRecords.addCallingInLandRecords(this); } } } else if(choice.equals("1")) { if(num[1].equals(this.getCallingNumber())) { if(this.getAnswerAddressAreaCode().matches("0791")) { userRecords.addCallingInCityRecords(this); } else if(this.getAnswerAddressAreaCode().matches("079[0-9]")|| this.getAnswerAddressAreaCode().matches("0701")) { userRecords.addCallingInProvinceRecords(this); } else { userRecords.addCallingInLandRecords(this); } } else if(num[1].equals(this.getAnswerNumber())) { if(this.getAnswerAddressAreaCode().matches("0791")) { userRecords.addAnswerInCityRecords(this); } else if(this.getAnswerAddressAreaCode().matches("079[0-9]")|| this.getAnswerAddressAreaCode().matches("0701")) { userRecords.addAnswerInProvinceRecords(this); } else { userRecords.addAnswerInLandRecords(this); } } } } public Date getStartTime () { return startTime; } public void setStartTime (Date startTime) { this.startTime = startTime; } public Date getEndTime () { return endTime; } public void setEndTime (Date endTime) { this.endTime = endTime; } public String getCallingAddressAreaCode () { return callingAddressAreaCode; } public void setCallingAddressAreaCode (String callingAddressAreaCode) { this.callingAddressAreaCode = callingAddressAreaCode; } public String getAnswerAddressAreaCode (){ return answerAddressAreaCode; } public void setAnswerAddressAreaCode (String answerAddressAreaCode){ this.answerAddressAreaCode = answerAddressAreaCode; } } abstract class CommunicationRecord{ protected String callingNumber; protected String answerNumber; public String getCallingNumber () { return callingNumber; } public void setCallingNumber (String callingNumber) { this.callingNumber = callingNumber; } public String getAnswerNumber () { return answerNumber; } public void setAnswerNumber (String answerNumber) { this.answerNumber = answerNumber; } } class MessageRecord extends CommunicationRecord{ private String massage; public void Deal(String a, UserRecords userRecords,String num) { String []mess = a.split(" "); if(mess[0].contains(num)) { this.setMessage(a.substring(26, a.length())); userRecords.addSendMessageRecords(this); } } public String getMessage(){ return massage; } // u-18907910010 3 // m-18907910010 13305862264 aaaaaaaaaaaaaaaaaaaaaaa // end public void setMessage (String message) { this.massage = message; } } abstract class ChargeMode{ protected ArrayList<ChargeRule> chargeRules = new ArrayList<>(); public abstract double calCost(UserRecords userRecords); public abstract double getMonthlyRent(); public ArrayList<ChargeRule> getChargeRules() { return chargeRules; } public void setChargeRules(ArrayList<ChargeRule> chargeRules) { this.chargeRules = chargeRules; } } class LandlinePhoneCharging extends ChargeMode{ double monthlyRent = 20; public LandlinePhoneCharging() { super(); this.getChargeRules ().add(new LandPhoneInCityRule()); this.getChargeRules ().add(new LandPhoneInProvinceRule()); this.getChargeRules ().add(new LandPhoneInlandRule()); } @Override public double calCost(UserRecords userRecords) { double sumCost = 0; for (ChargeRule a : chargeRules) { sumCost += a.calCost(userRecords); } return sumCost; } @Override public double getMonthlyRent() { return monthlyRent; } } class PhoneChaging extends ChargeMode{ double monthlyRent = 15; public PhoneChaging() { super(); this.getChargeRules ().add(new PhoneInCityRule()); this.getChargeRules ().add(new PhoneInProvinceRule()); this.getChargeRules ().add(new PhoneInlandRule()); } @Override public double calCost(UserRecords userRecords) { double sumCost = 0; for (ChargeRule a : chargeRules) { sumCost += a.calCost(userRecords); } return sumCost; } @Override public double getMonthlyRent() { return monthlyRent; } } class MassageChaging extends ChargeMode{ public MassageChaging() { super(); this.getChargeRules ().add(new SendMessageRule()); } @Override public double calCost(UserRecords userRecords) { double sumCost = 0; for (ChargeRule a : chargeRules) { sumCost += a.calCost(userRecords); } return sumCost; } @Override public double getMonthlyRent() { return 0; } } abstract class ChargeRule{ protected abstract double calCost(UserRecords userRecords); } abstract class CallChargeRule extends ChargeRule{ public double calCost (CallRecord callRecords) { return 0; } } class LandPhoneInCityRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInCityRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } sumCost += timec * 0.1; } return sumCost; } } class LandPhoneInlandRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInLandRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } sumCost += timec * 0.6; } return sumCost; } } class LandPhoneInProvinceRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInProvinceRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } sumCost += timec * 0.3; } return sumCost; } } class PhoneInCityRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInCityRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } if(a.getCallingAddressAreaCode().matches("0971")) sumCost += timec * 0.1; else if(a.getAnswerAddressAreaCode().matches("079[0-9]")|| a.getAnswerAddressAreaCode().matches("0701")) sumCost += timec * 0.3; else sumCost += timec * 0.6; } return sumCost; } } class PhoneInProvinceRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInProvinceRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } if(a.getCallingAddressAreaCode().matches("0971")) sumCost += timec * 0.2; else if(a.getAnswerAddressAreaCode().matches("079[0-9]")|| a.getAnswerAddressAreaCode().matches("0701")) sumCost += timec * 0.3; else sumCost += timec * 0.6; } return sumCost; } } class PhoneInlandRule extends CallChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; for (CallRecord a: userRecords.getCallingInLandRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } if(a.getCallingAddressAreaCode().matches("0791")) sumCost += timec * 0.3; else if(a.getAnswerAddressAreaCode().matches("079[0-9]")|| a.getAnswerAddressAreaCode().matches("0701")) sumCost += timec * 0.3; else sumCost += timec * 0.6; } for (CallRecord a: userRecords.getAnswerInLandRecords()) { double time = (a.getEndTime().getTime()-a.getStartTime().getTime())/1000; if (time < 0) { continue; } double timec = (int) time / 60; if (time % 60 != 0) { timec += 1; } sumCost += timec * 0.3; } return sumCost; } } abstract class MessageChargeRule extends ChargeRule{ @Override protected double calCost(UserRecords userRecords) { return 0; } } class SendMessageRule extends MessageChargeRule{ @Override protected double calCost(UserRecords userRecords) { double sumCost = 0; double set = 0; int n = userRecords.getSendMessageRecords().size(); for(MessageRecord a: userRecords.getSendMessageRecords()) { int sum = a.getMessage().length(); int b=0; if(sum>10) { if(sum%10!=0) { b=sum/10; n+=b; } else { b=sum/10; n+=b-1; } } } if(n>=1&&n<=3) { sumCost+=0.1*n; } else if(n>3&&n<=5) { sumCost+=0.2*(n-3)+0.1*3; } else { if(n>0) { if(n<=8) { sumCost+=0.3*5+0.1*(n-5); } else { sumCost+=0.3*(n-5)+0.2*2+0.1*3; } } } return sumCost; } }View Code
踩坑心得
通过本次作业,强化了我对正则表达式的理解,然后有一个技巧就是当我们在判断的时候可能会因为代码太长发生错误,这时我们可以将字符串通过以空格分离然后再进行匹配,大事化小。
改进建议
对于该类题目代码的改进应该就是继续通过剩下的测试点和将代码改进得更加简洁和要多添加一些注释。
二、农夫过河
实验四
重构实验二中农夫过河游戏的代码,并且根据前几次的实验适当地添加方法来进行农夫过河的游戏。
实验五
修改实验四农夫过河游戏的代码,将用户界面改为图形界面,界面效果自行设计。
解释分析
这几次实验都是农夫过河,从之前的四五个类到现在的十几个类,还加上了父类,多态,接口,最后到实验五的javafx,总的来说就是难度越来越大了,但是因为实验是一步一步递进的,所以这个还是比PTA好写一点的。就是javafx因为线上网课和自身的抽象性所以还要自己学习一下,因此实验五做的比较简陋,只能是说得过去。
类图
代码如下
实验五:
package application; import java.util.ArrayList; import java.util.HashSet; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.stage.Stage; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class Main extends Application { @Override public void start(Stage primaryStage) { Game game = new Game(); Button b1 = new Button(); b1.setText("开始游戏"); b1.setLayoutX(250); b1.setLayoutY(240); b1.setPrefWidth(100); b1.setPrefHeight(50); Button b2 = new Button(); b2.setText("游戏说明"); b2.setLayoutX(250); b2.setLayoutY(320); b2.setPrefWidth(100); b2.setPrefHeight(50); Button b3 = new Button(); b3.setText("退出游戏"); b3.setLayoutX(500); b3.setLayoutY(550); b3.setPrefWidth(100); b3.setPrefHeight(50); Group group = new Group(); group.getChildren().addAll(b1,b3,b2); Scene scene = new Scene(group,600,600); primaryStage.setTitle("农夫过河"); primaryStage.setScene(scene); primaryStage.show(); b1.setOnAction(e->game.play()); b3.setOnAction(e->primaryStage.close()); b2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Stage secondStage = new Stage(); Group group1 = new Group(); Scene secondScene = new Scene(group1,600,600); secondStage.setScene(secondScene); secondStage.show(); Button b3 = new Button(); b3.setText("返回"); b3.setLayoutX(500); b3.setLayoutY(550); b3.setPrefWidth(100); b3.setPrefHeight(50); Text t = new Text("请选择不同的过河 方式,让农夫顺利带着狼,羊和菜过河。\n(注意:当农夫不在的时候狼会吃羊,羊会吃白菜。)"); t.setCache(true); t.setX(10.0); t.setY(70.0); t.setFill(Color.RED); t.setFont(Font.font(null, FontWeight.BOLD, 22)); group1.getChildren().add(t); group1.getChildren().add(b3); b3.setOnAction(e->secondStage.close()); } }); } public static void main(String[] args) { launch(args); } } abstract class AbstractGame { public abstract void play(); } class Game extends AbstractGame { private GameOverRule gameOverRule = new GameOverRule(); private GameSuccessRule gameSuccessRule = new GameSuccessRule();; private GameData gameData; private int choice; public void run(Stage thirdStage) { GameUI gameui = new GameUI(); boolean gameOver=false,win=false; switch(choice){ case 1: gameData.Boat.crossRiver(gameData.farmer); break; case 2: if(gameData.farmer.Getplace().equals(gameData.wolf.Getplace())) gameData.Boat.crossRiver(gameData.farmer, gameData.wolf); else System.out.println("两者不在同一河岸,请重新输入!"); break; case 3: if(gameData.farmer.Getplace().equals(gameData.sheep.Getplace())) gameData.Boat.crossRiver(gameData.farmer, gameData.sheep); else System.out.println("两者不在同一河岸,请重新输入!"); break; case 4: if(gameData.farmer.Getplace().equals(gameData.cabbage.Getplace())) gameData.Boat.crossRiver(gameData.farmer, gameData.cabbage); else System.out.println("两者不在同一河岸,请重新输入!"); break; } gameData.Boat.moveTo(gameData.Boat.Getplace()); gameData.wolf.eat(gameData.farmer,gameData.sheep); gameData.sheep.eat(gameData.farmer,gameData.cabbage); gameOver = gameOverRule.judge(gameData.wolf,gameData.sheep,gameData.cabbage); if(gameOver) { win= gameSuccessRule.judge(gameData.wolf,gameData.sheep,gameData.cabbage); if(win){ gameui.showWin(thirdStage); } else{ gameui.showFail(thirdStage,this.gameData); } } } public void play() { gameData = new GameData(); Stage thirdStage = new Stage(); Label label = new Label("请选择:"); Pane pane = new Pane(); Scene thirdScene = new Scene(pane,600,600); Image river = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\河.jpg",300,600,false,false); ImageView he = new ImageView(river); he.setX(150); pane.getChildren().addAll(he,this.gameData.farmer.photo(),this.gameData.wolf.photo(), this.gameData.sheep.photo(),this.gameData.cabbage.photo(), this.gameData.Boat.photo()); HBox hb = new HBox(5); Button []b = new Button[4]; for(int i = 0;i<4;i++) { b[i] = new Button(); } b[0].setText("农夫独自过河"); b[1].setText("农夫带狼过河"); b[2].setText("农夫带羊过河"); b[3].setText("农夫带菜过河"); hb.getChildren().add(label); hb.getChildren().addAll(b); pane.getChildren().add(hb); thirdStage.setScene(thirdScene); thirdStage.show(); b[0].setOnAction(e->{ this.choice = 1; run(thirdStage); }); b[1].setOnAction(e->{ this.choice = 2; run(thirdStage); }); b[2].setOnAction(e->{ this.choice = 3; run(thirdStage); }); b[3].setOnAction(e->{ this.choice = 4; run(thirdStage); }); } } class GameData{ Person farmer; Plant cabbage; Wolf wolf; Sheep sheep; Boat Boat; GameData(){ farmer = new Person(); cabbage = new Plant(); wolf = new Wolf(); sheep = new Sheep(); Boat = new Boat(); wolf.addedToRecipe(this.sheep); sheep.addedToRecipe(this.cabbage); } } abstract class AbstractRule { public boolean judge(Wolf wolf, Sheep sheep, Plant cabbage) { return true; } //根据规则判断结果 } class CrossRiverRule extends AbstractRule { CrossRiverRule(){ } public boolean hasCross(MaterialObject m){ if(m.Getplace().equals("河对岸")) { return true; } return false; } } class GameOverRule extends AbstractRule { CrossRiverRule crossriverrule; ObjectExistRule objectexisteule; GameOverRule(){ crossriverrule = new CrossRiverRule(); objectexisteule = new ObjectExistRule(); } public boolean judge(Wolf wolf, Sheep sheep, Plant cabbage) { if(!objectexisteule.ObjectExist(sheep)||!objectexisteule.ObjectExist(cabbage)){ return true; } if(crossriverrule.hasCross(wolf)&&crossriverrule.hasCross(sheep)&&crossriverrule.hasCross(cabbage)){ return true; } return false; } } class GameSuccessRule extends AbstractRule { CrossRiverRule crossriverrule; ObjectExistRule objectexisteule; GameSuccessRule(){ crossriverrule = new CrossRiverRule(); objectexisteule = new ObjectExistRule(); } public boolean judge(Wolf wolf, Sheep sheep, Plant cabbage) { if(!objectexisteule.ObjectExist(sheep)||!objectexisteule.ObjectExist(cabbage)){ return false; } if(crossriverrule.hasCross(wolf)&&crossriverrule.hasCross(sheep)&&crossriverrule.hasCross(cabbage)){ return true; } return false; } } class Person extends MaterialObject { Person(){ this.image = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\农夫.jpg",150,150,false,false); this.imageView = new ImageView(); } public ImageView photo() { imageView.setImage(image); return imageView; } // public void showStatus() { // System.out.println(this.Gettype()+"在"+this.Getplace()); // } } class Plant extends MaterialObject { Plant(){ this.image = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\菜.jpg",150,150,false,false); this.imageView = new ImageView(); } public ImageView photo() { imageView.setImage(image); imageView.setX(0); imageView.setY(450); return imageView; } public Plant(String name) { super.Settype(name); } } class Sheep extends MaterialObject { Image image = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\羊.jpg",150,150,false,false); ImageView imageView = new ImageView(); Sheep(){ } public ImageView photo() { imageView.setImage(image); imageView.setX(0); imageView.setY(300); return imageView; } } class Wolf extends MaterialObject { Wolf(){ this.image = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\狼.jpg",150,150,false,false); this.imageView = new ImageView(); } public ImageView photo() { imageView.setImage(image); imageView.setX(0); imageView.setY(150); return imageView; } } class Boat extends MaterialObject implements AbstracTransport { Boat(){ this.image = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\船.jpg",150,300,false,false); this.imageView = new ImageView(); } public ImageView photo() { imageView.setImage(image); imageView.setX(150); imageView.setY(150); return imageView; } public void crossRiver(Person farmer){//将人运载过河 this.board(farmer); this.Setplace(); if(this.Getplace().equals("河对岸")) { this.imageView.setX(300); } else { this.imageView.setX(150); } } public void crossRiver(Person farmer,MaterialObject m) { this.board(farmer); this.board(m); this.Setplace(); if(this.Getplace().equals("河对岸")) { this.photo().setX(300); } else { this.photo().setX(150); } }//将人和某样物品运载过河 public void board(MaterialObject m) {//在船上 this.addgoodses(m); this.disembark(m); } public void disembark(MaterialObject m) {//物品m下船 m.Setplace(); m.Setphoto(); } public void addgoodses(MaterialObject m) { if(goodses.size()==0) { goodses.add(m); //System.out.println(goodses.get(capacity-2).Gettype()+"已上船"); } else { goodses.add(m); //System.out.println(goodses.get(capacity-1).Gettype()+"已上船"); } } public void moveTo(String destination){//目的地 //System.out.println("船已经行驶到了"+destination); goodses.clear(); } } interface AbstracTransport { public static final String place = ""; public static final int capacity = 2; public static final ArrayList<MaterialObject> goodses = new ArrayList<>();//货物列表 public abstract void moveTo(String destination); public abstract void addgoodses(MaterialObject m); } abstract class MaterialObject { private String type; private String place = "河岸"; private boolean isExist = true; private HashSet<MaterialObject> recipe = new HashSet<>();//食谱 Image image; ImageView imageView; public void diedOut() { this.isExist = false; } public ImageView photo() { return imageView; } public void Setphoto() { if(this.Getplace().equals("河对岸")) { this.photo().setX(450); } else { this.photo().setX(0); } } public boolean isExist() { return isExist; } public void Settype(String name) { type=name; } public String Gettype() { return type; } public void Setplace() { if(place.equals("河岸")) { this.place = "河对岸"; } else { this.place = "河岸"; } } public String Getplace() { return place; } // public void showStatus() { // String life="活着"; // if(!this.isExist()) { // life = "已被吃"; // } // System.out.print(this.type+"的生存状态:"+life+" "); // System.out.println(this.type+"在"+this.Getplace()); // } public boolean eat(MaterialObject farmer,MaterialObject m) {//吃某样食物 if(canBeEat(farmer,m)) { m.diedOut(); } return true; } public void addedToRecipe(MaterialObject m) {//添加某物品进该动物的食谱 recipe.add(m); } public boolean isfood(MaterialObject m) {//判断某物品是否在它的食谱中 for(MaterialObject i:recipe) { if(i==m) { return true; } } return false; } public boolean canBeEat(MaterialObject farmer,MaterialObject m) {//判断某物品能不能被吃到 if(this.isfood(m)) { if(!farmer.Getplace().equalsIgnoreCase(this.Getplace())&& m.Getplace().equalsIgnoreCase(this.Getplace())) { return true; } } return false; } } class ObjectExistRule extends AbstractRule { ObjectExistRule(){ } public boolean ObjectExist(MaterialObject m) { if(m.isExist()) { return true; } return false; } } class GameUI { Stage fourthStage = new Stage(); Pane pane = new Pane(); Scene thirdScene = new Scene(pane,600,600); public void showWin(Stage thirdStage) { thirdStage.close(); Image win = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\赢了.jpg",600,600,false,false); ImageView ying = new ImageView(win); this.pane.getChildren().add(ying); this.fourthStage.setScene(this.thirdScene); fourthStage.show(); } public void showFail(Stage thirdStage, GameData gameData){ thirdStage.close(); if(!gameData.sheep.isExist()&&!gameData.cabbage.isExist()) { Image win = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\输没了.jpg",600,600,false,false); ImageView ying = new ImageView(win); this.pane.getChildren().add(ying); this.fourthStage.setScene(this.thirdScene); fourthStage.show(); } else { if(!gameData.sheep.isExist()) { Image win = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\羊死了.jpg",600,600,false,false); ImageView ying = new ImageView(win); this.pane.getChildren().add(ying); this.fourthStage.setScene(this.thirdScene); fourthStage.show(); } else if(!gameData.cabbage.isExist()) { Image win = new Image("file:\\C:\\Users\\zsx\\Desktop\\图片\\菜死了.jpg",600,600,false,false); ImageView ying = new ImageView(win); this.pane.getChildren().add(ying); this.fourthStage.setScene(this.thirdScene); fourthStage.show(); } } } }View Code
实验效果:
踩坑心得
实验四还好,也是看类图补代码,而且有前几次的实验的基础,所以比较好些。而实验五是我第一次用javafx写的代码,所以比较废脑袋是不假的,但是在写的过程中能够看到自己写的成果,也是一种比较有成就感的事,也就没有平时写代码适当枯燥。所以写代码一定要勇敢面对它,而不是不敢下手,不然等到时间过了才后悔。还有一定要善于运用网上的资源,不会的一定要去查,去问。
改进建议
将代码变得更加清晰和易懂,而且要友好。
总结
关于对本学期的总结,总的来说,其实对自己的表现并不满意,因为是线上上课,所以没有管好自己,以至于对所学的东西都是相当模糊的概念,作业也做得不好。可是总归还是学到了一些东西,就是学的不深。老师讲的都是懂的不会去复习,不懂的也会拖一阵子才去弄懂,有些时候跟不上上课节奏。即使如此,我还是会按时完成实验和其他编程作业,在做作业的时候加强对知识的理解。本学期从对java什么都不懂到现在能写一些面向对象的程序设计,收获很多,但是遗憾也很多,所以以后要好好学习了,多多动手去编程,去看好的代码,跟着学,尽量让自己不后悔没好好学。
标签:return,String,matches,void,Blog,new,public 来源: https://www.cnblogs.com/zsx1234/p/16389070.html