标签:return String ArrayList blog cost new public
前言
总结期中考试涉及到的知识点,题量,难度的情况。期中考试一共有三题,难度逐步增加,逐渐考察了类的相关设计。第一题考察了基础的类的设计。第二题考察了类设计中的继承和多态。第三题考察了多态类的设计。期中考试难度不大,主要考察类的设计和根据类图设计类的能力。
总结PTA题目集涉及到的知识点,题量,难度的情况。PTA题目集中的PTA大作业四一共有三题。第一题考察了正则表达式。第二题属于点——线系列的题目。第三题考察了类的设计。总体难度适中,考察的知识点多样丰富,其中点——线系列考察了很多的数学知识。
设计与分析
对电信计费题目的代码进行分析
电信计费题仔细分析下可以发现,整个流程就是从输入框获取信息,然后对获取的信息进行处理,分类,然后将处理后的信息再输出到控制台。
我以此思路为基础,写了两个用与处理信息的类,分别用与获取信息并将其处理分析,以规定的格式保存在ArrayList<Record>中,然后再将其分别找到对应的客户然后将通话记录分配给这个用户,然后在另外一个处理信息的类中输出需要的信息。
在整个做题过程我发现最难的一步在于写出一个正确的正则表达式,每次都是错误的处理的信息。
再后续的电信计费题目中,我将正则表达式写对了就得到了满分。
我在这里贴出我的三次正则表达式的代码:
这是我第一次只得了38分的正则表达式
String regex_u = "^u+(-)+[0-9]{11,12}\\s+[0-2]$";//开户格式的判断正则表达式
Pattern pattern_u = Pattern.compile(regex_u);
String regex_t = "^t+(-)+[0-9]{11,12}\\s+[0-9]{11,12}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
Pattern pattern_t = Pattern.compile(regex_t);
这是第二次电信计费题我的满分正则表达式
String regexLandToMobile = "^t-([0][0-9]{9,11})\\s([1][0-9]{10})\\s([0-9]{3,5})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexLandToLand = "^t-([0][0-9]{9,11})\\s([0][0-9]{9,11})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexMobileToLand = "^t-([1][0-9]{10})\\s([0-9]{3,5})\\s([0][0-9]{9,11})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexMobileToMobile = "[t]-1[0-9]{10}\\s[0-9]{3,4}\\s1[0-9]{10}\\s[0-9]{3,4}\\s((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})\\.(((0?[13578]|1[02])\\.(0?[1-9]|[12][0-9]|3[01]))|(([469]|11)\\.([1-9]|[12][0-9]|30))|(2\\.([1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})([48]|[2468][048]|[13579][26])|(([48]|[2468][048]|[3579][26])00))\\\\.2\\\\.29))\\s([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])\\s((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})\\.((([13578]|1[02])\\.([1-9]|[12][0-9]|3[01]))|(([469]|11)\\.([1-9]|[12][0-9]|30))|(2\\.([1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})([48]|[2468][048]|[13579][26])|(([48]|[2468][048]|[3579][26])00))\\.2\\.29))\\s([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";//"^t-([1][0-9]{10})\\s([0-9]{3,5})\\s([1][0-9]{10})\\s([0-9]{3,5})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
这是第三次满分的正则表达式:
String regexUser = "^u-([1][0-9]{10})\\s[3]$";
String regexMessage = "^m-1[0-9]{10}\\s1[0-9]{10}\\s(\\w|\\s|,|[.])+$";
电信计费的题目的思路很简单,就难在怎么写出一个正确的正则表达式
以下是我第二次电信计费题的类图:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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) {
ArrayList<User> users = HeaderInput.header();
HeaderOutput.header(users);
}
}
class CallRecord extends CommunicationRecord{
private Date startTime ;
private Date endTime;
private int time_minute;
private String callingAddressAreaCode ;
private String answerAddressAreaCode;
public CallRecord ( ) {
}
public CallRecord (Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode) {
this.startTime = startTime;
this.endTime = endTime;
this.callingAddressAreaCode = callingAddressAreaCode;
this.answerAddressAreaCode = answerAddressAreaCode;
double s_time = startTime.getTime()/(1000);//获取分钟
double e_time = endTime.getTime()/(1000);
double time1 = e_time - s_time;
time1 = time1 /60;
int time = (int)time1;
if(time!=time1)
time++;
time_minute = time;
}
public void countTime_minute()
{
double s_time = startTime.getTime()/(1000);//获取分钟
double e_time = endTime.getTime()/(1000);
double time1 = e_time - s_time;
time1 = time1 /60;
int time = (int)time1;
if(time!=time1)
time++;
time_minute = time;
}
public int getTime_minute ( ) {
return time_minute;
}
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 ChargeMode {
private ArrayList<ChargeRule> chargeRules = new ArrayList<ChargeRule>();
public abstract double calCost(UserRecords userRecords);
public abstract double getMonthlyRent();
/*Get和Set方法*/
public ArrayList<ChargeRule> getChargeRules() {
return chargeRules;
}
public void setChargeRules(ArrayList<ChargeRule> chargeRules) {
this.chargeRules = chargeRules;
}
}
abstract class ChargeRule {
public abstract double calCost(ArrayList<CallRecord> callRecords);
}
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 HeaderInput {
/*对一行的输入进行分析 ,区别开户,和通讯信息
* 注意区分错误输入
* */
/*对所有的信息进行处理,返回用户列表*/
public static ArrayList<User> header()
{
Scanner input = new Scanner(System.in);
ArrayList<String> data = new ArrayList<>();
/*获取信息输入*/
String tmp = input.nextLine();
while( !tmp.equals("end"))
{
data.add(tmp);
tmp = input.nextLine();
}
/*对信息进行处理*/
/*利用正则表达式进行格式判断*/
String regexMobile = "^u-([1][0-9]{10})\\s[1]$";
String regexLand = "^u-([0][0-9]{9,11})\\s[0]$";//开户格式的判断正则表达式
Pattern patternMobile = Pattern.compile(regexMobile);
Pattern patternLand = Pattern.compile(regexLand);
String regexLandToMobile = "^t-([0][0-9]{9,11})\\s([1][0-9]{10})\\s([0-9]{3,5})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexLandToLand = "^t-([0][0-9]{9,11})\\s([0][0-9]{9,11})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexMobileToLand = "^t-([1][0-9]{10})\\s([0-9]{3,5})\\s([0][0-9]{9,11})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
String regexMobileToMobile = "[t]-1[0-9]{10}\\s[0-9]{3,4}\\s1[0-9]{10}\\s[0-9]{3,4}\\s((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})\\.(((0?[13578]|1[02])\\.(0?[1-9]|[12][0-9]|3[01]))|(([469]|11)\\.([1-9]|[12][0-9]|30))|(2\\.([1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})([48]|[2468][048]|[13579][26])|(([48]|[2468][048]|[3579][26])00))\\\\.2\\\\.29))\\s([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])\\s((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})\\.((([13578]|1[02])\\.([1-9]|[12][0-9]|3[01]))|(([469]|11)\\.([1-9]|[12][0-9]|30))|(2\\.([1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})([48]|[2468][048]|[13579][26])|(([48]|[2468][048]|[3579][26])00))\\.2\\.29))\\s([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";//"^t-([1][0-9]{10})\\s([0-9]{3,5})\\s([1][0-9]{10})\\s([0-9]{3,5})\\s[0-9]{4}(.)((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}\\s+[0-9]{4}+(.)+((0?[1-9])|([10-12]))+(.)+[0-9]{1,2}$";
Pattern patternLandToMobile = Pattern.compile(regexLandToMobile);
Pattern patternLandToLand = Pattern.compile(regexLandToLand);
Pattern patternMobileToLand = Pattern.compile(regexMobileToLand);
Pattern patternMobileToMobile = Pattern.compile(regexMobileToMobile);
HashSet<String> stringLand = new HashSet<>();
HashSet<String> stringMobile = new HashSet<>();
ArrayList<CallRecord> callRecords = new ArrayList<>();
for(int i = 0;i<data.size();i++)
{
String target = data.get(i);
Matcher matcherLand = patternLand.matcher(target);
Matcher matcherMobile = patternMobile.matcher(target);
Matcher matcherLandToLand = patternLandToLand.matcher(target);
Matcher matcherLandToMobile = patternLandToMobile.matcher(target);
Matcher matcherMobileToLand = patternMobileToLand.matcher(target);
Matcher matcherMobileToMobile = patternMobileToMobile.matcher(target);
if(matcherLand.find())
{
stringLand.add(target);
}
if (matcherMobile.find()) {
stringMobile.add(target);
}
if(matcherLandToLand.find())
{
callRecords.add(LandToLand(target));
}
if (matcherLandToMobile.find()) {
callRecords.add(LandToPhone(target));
}
if (matcherMobileToLand.find()) {
callRecords.add(PhoneToLand(target));
}
if (matcherMobileToMobile.find()) {
callRecords.add(PhoneToPhone(target));
}
}
ArrayList<User> users = new ArrayList<>();
ArrayList<String> LandList = new ArrayList<>();
ArrayList<String> Mobilelist = new ArrayList<>();
for (String e : stringLand) {
LandList.add(e);
}
for (String e : stringMobile) {
Mobilelist.add(e);
}
for (String e : LandList) {
users.add(createLand(e));
}
for (String e : Mobilelist) {
users.add(createMobile(e));
}
/*最终得到一个用户集合users,通话集合callRecords*/
/*遍历通话集合,进行划分*/
/*将信息分给每个用户*/
for(int i = 0; i< callRecords.size(); i++)
{
CallRecord callRecord = callRecords.get(i);
String callNumber = callRecord.getCallingNumber();
String answerNumber = callRecord.getAnswerNumber();
String callArea = callRecord.getCallingAddressAreaCode();
String answerArea = callRecord.getAnswerAddressAreaCode();
User callUser;
User answerUser;
callUser = findUser(users,callNumber);
answerUser = findUser(users,answerNumber);
if(callUser != null)
{
if(answerArea.equals("0791"))
callUser.getUserRecords().addCallingLnCityRecords(callRecord);
else if((answerArea.compareTo("0790")>=0 && answerArea.compareTo("0799")<=0)||(answerArea.equals("0701")))
callUser.getUserRecords().addCallingLnProvinceRecords(callRecord);
else
callUser.getUserRecords().addCallingLnRecords(callRecord);
}
if(answerUser != null)
{
if(answerArea.equals("0791"))
answerUser.getUserRecords().addAnswerLnCityRecords(callRecord);
else if((answerArea.compareTo("0790")>=0 && answerArea.compareTo("0799")<=0)||(answerArea.equals("0701")))
answerUser.getUserRecords().addAnswerLnProvinceRecords(callRecord);
else
answerUser.getUserRecords().addAnswerLnRecords(callRecord);
}
}
/*返回用户列表*/
return users;
}
/*根据电话号码寻找用户*/
private static User findUser(ArrayList<User> users,String number)
{
for(int i= 0;i<users.size();i++)
{
if(number.equals(users.get(i).getNumber()))
return users.get(i);
}
return null;
}
private static User createLand(String str)
{
User user = new User();
String temp[] = str.split("-");
temp = temp[1].split(" ");
String number = temp[0];
user.setNumber(number);
ArrayList<ChargeRule> chargeRules = new ArrayList<>();
chargeRules.add(new LandPhoneLnCityRule());
chargeRules.add(new LandPhoneLnProvinceRule());
chargeRules.add(new LandPhoneLnlandRule());
LandlinePhoneCharging landlinePhoneCharging = new LandlinePhoneCharging();
landlinePhoneCharging.setChargeRules(chargeRules);
user.setChargeMode(landlinePhoneCharging);
return user;
}
private static User createMobile(String str)
{
User user = new User();
String temp[] = str.split("-");
temp = temp[1].split(" ");
String number = temp[0];
user.setNumber(number);
ArrayList<ChargeRule> MobilePhoneChargeRules = new ArrayList<>();
MobilePhoneChargeRules.add(new MobilePhoneLnCityRule());
MobilePhoneChargeRules.add(new MobilePhoneLnProvinceRule());
MobilePhoneChargeRules.add(new MobilePhoneLnlandRule());
MobilePhoneChargeRules.add(new MobilePhoneAnswerLnProvinceRule());
MobilePhoneChargeRules.add(new MobilePhoneAnswerLnlandRule());
MobilePhoneCharging mobilePhoneCharging = new MobilePhoneCharging();
mobilePhoneCharging.setChargeRules(MobilePhoneChargeRules);
user.setChargeMode(mobilePhoneCharging);
return user;
}
/*处理座机打座机*/
private static CallRecord LandToLand(String str)
{
String temp[] = str.split("-");
temp = temp[1].split(" ");
String callNumber = temp[0],answerNumber = temp[1],startTime = temp[2]+" "+ temp[3],endTime = temp[4]+" "+ temp[5];
/*处理时间*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = sdf.parse(startTime);
endDate = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
CallRecord callRecord = new CallRecord(startDate, endDate, callNumber.substring(0, 4), answerNumber.substring(0, 4));
callRecord.setCallingNumber(callNumber);
callRecord.setAnswerNumber(answerNumber);
/*------------------*/
return callRecord;
}
/*处理座机打手机*/
private static CallRecord LandToPhone(String str)
{
String temp[] = str.split("-");
temp = temp[1].split(" ");
String callNumber = temp[0] , answerNumber = temp[1] ;
String callArea = callNumber.substring(0,4), answerArea = temp[2];
String startTime = temp[3]+" "+temp[4] , endTime = temp[5]+" "+temp[6];
/*处理时间*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = sdf.parse(startTime);
endDate = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
CallRecord callRecord = new CallRecord(startDate, endDate, callArea,answerArea);
callRecord.setCallingNumber(callNumber);
callRecord.setAnswerNumber(answerNumber);
/*------------------*/
return callRecord;
}
/*处理手机打座机*/
private static CallRecord PhoneToLand (String str)
{
String temp[] = str.split("-");
temp = temp[1].split(" ");
String callNumber = temp[0],answerNumber = temp[2];
String callArea = temp[1] , answerArea = answerNumber.substring(0,4);
String startTime = temp[3]+" "+temp[4] , endTime = temp[5]+" "+temp[6];
/*处理时间*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = sdf.parse(startTime);
endDate = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
CallRecord callRecord = new CallRecord(startDate, endDate, callArea,answerArea);
callRecord.setCallingNumber(callNumber);
callRecord.setAnswerNumber(answerNumber);
callRecord.countTime_minute();
/*------------------*/
return callRecord;
}
/*处理手机打手机*/
private static CallRecord PhoneToPhone(String str)
{
String temp[] = str.split("-");
temp = temp[1].split(" ");
String callNumber = temp[0],answerNumber = temp[2];
String callArea = temp[1] , answerArea = temp[3];
String startTime = temp[4]+" "+temp[5] , endTime = temp[6]+" "+temp[7];
/*处理时间*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date startDate = new Date();
Date endDate = new Date();
try {
startDate = sdf.parse(startTime);
endDate = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
CallRecord callRecord = new CallRecord(startDate, endDate, callArea,answerArea);
callRecord.setCallingNumber(callNumber);
callRecord.setAnswerNumber(answerNumber);
/*------------------*/
return callRecord;
}
}
class HeaderOutput {
public static void header(ArrayList<User> users)
{
ArrayList<User> user11 = sortUser(users);
for(int i=0;i<user11.size();i++)
{
user11.get(i).calBalance();
System.out.printf("%s %.1f %.1f\n",user11.get(i).getNumber(),user11.get(i).calCost(),user11.get(i).getBalance());
}
}
public static ArrayList<User> sortUser(ArrayList<User> users)
{
int min = 0;
ArrayList<User> userArrayList = new ArrayList<>();
User[] arr = new User[users.size()];
for(int i = 0;i<users.size();i++)
{
arr[i] = users.get(i);
}
for(int i = 0;i<users.size();i++)
{
min = i;
for(int k=i+1;k<users.size();k++)
{
if(arr[k].getNumber().compareTo(arr[min].getNumber())<0)
{
min = k;
}
}
if(min!=i)
{
User tmp = users.get(min);
arr[min] = arr[i];
arr[i] = tmp;
}
}
for(int i= 0;i<users.size();i++)
{
userArrayList.add(arr[i]);
}
return userArrayList;
}
}
class LandlinePhoneCharging extends ChargeMode{
private double monthlyRent = 20.0;
/*获取所有类型的通讯信息的花费*/
@Override
public double calCost(UserRecords userRecords) {
ArrayList<ChargeRule> chargeRules = this.getChargeRules();
// LandPhoneLnCityRule landPhoneLnCityRule = (LandPhoneLnCityRule) chargeRules.get(0);
// LandPhoneLnProvinceRule landPhoneLnProvinceRule = (LandPhoneLnProvinceRule) chargeRules.get(1);
// LandPhoneLnlandRule landPhoneLnlandRule = (LandPhoneLnlandRule) chargeRules.get(2);
double cost = 0;
cost = cost + chargeRules.get(0).calCost(userRecords.getCallingLnCityRecords());
cost = cost + chargeRules.get(1).calCost(userRecords.getCallingLnProvinceRecords());
cost = cost + chargeRules.get(2).calCost(userRecords.getCallingLnRecords());
return cost;
}
@Override
public double getMonthlyRent() {
return monthlyRent;
}
}
class LandPhoneLnCityRule extends ChargeRule{
@Override
public double calCost(ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
/*市内拨打电话0.1元/分钟*/
cost = cost+ 0.1*time;
}
return cost;
}
}
class LandPhoneLnlandRule extends ChargeRule{
@Override
public double calCost(ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
cost = cost+ 0.6*time;
}
return cost;
}
}
class LandPhoneLnProvinceRule extends ChargeRule{
@Override
public double calCost(ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
cost = cost+ 0.3*time;
}
return cost;
}
}
class MessageRecord extends CommunicationRecord{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class User {
private UserRecords userRecords = new UserRecords();
private double balance = 100;
private ChargeMode chargeMode;
private String number ;
/*计算当前通话信息的余额*/
public double calBalance()
{
double balance = this.balance - this.calCost()-chargeMode.getMonthlyRent();
this.balance = balance;
return balance;
}
/*计算当前通话信息的花费 */
public double calCost()
{
return chargeMode.calCost(userRecords);
}
public UserRecords getUserRecords() {
return userRecords;
}
public void setUserRecords(UserRecords userRecords) {
this.userRecords = userRecords;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
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> callingLnCityRecords = new ArrayList<>();
private ArrayList<CallRecord> callingLnProvinceRecords = new ArrayList<>();
private ArrayList<CallRecord> callingLnRecords = new ArrayList<>();
private ArrayList<CallRecord> answerLnCityRecords = new ArrayList<>();
private ArrayList<CallRecord> answerLnProvinceRecords = new ArrayList<>();
private ArrayList<CallRecord> answerLnRecords = new ArrayList<>();
private ArrayList<MessageRecord> sendMessageRecords = new ArrayList<>();
private ArrayList<MessageRecord> receiveMessageRecords = new ArrayList<>();
public void addCallingLnCityRecords(CallRecord callingLnCityRecords) {
this.callingLnCityRecords.add(callingLnCityRecords);
}
public void addCallingLnProvinceRecords(CallRecord callingLnProvinceRecords) {
this.callingLnProvinceRecords.add(callingLnProvinceRecords);
}
public void addCallingLnRecords(CallRecord callingLnRecords) {
this.callingLnRecords.add(callingLnRecords);
}
public void addAnswerLnCityRecords(CallRecord answerLnCityRecords) {
this.answerLnCityRecords.add(answerLnCityRecords);
}
public void addAnswerLnProvinceRecords(CallRecord answerLnProvinceRecords) {
this.answerLnProvinceRecords.add(answerLnProvinceRecords);
}
public void addAnswerLnRecords(CallRecord answerLnRecords) {
this.answerLnRecords.add(answerLnRecords);
}
public void addSendMessageRecords(MessageRecord sendMessageRecords) {
this.sendMessageRecords.add(sendMessageRecords);
}
public void addReceiveMessageRecords(MessageRecord receiveMessageRecords) {
this.receiveMessageRecords.add(receiveMessageRecords);
}
public ArrayList<CallRecord> getCallingLnProvinceRecords() {
return callingLnProvinceRecords;
}
public ArrayList<CallRecord> getCallingLnRecords() {
return callingLnRecords;
}
public ArrayList<CallRecord> getAnswerLnCityRecords() {
return answerLnCityRecords;
}
public ArrayList<CallRecord> getAnswerLnProvinceRecords() {
return answerLnProvinceRecords;
}
public ArrayList<CallRecord> getAnswerLnRecords() {
return answerLnRecords;
}
public ArrayList<MessageRecord> getSendMessageRecords() {
return sendMessageRecords;
}
public ArrayList<MessageRecord> getReceiveMessageRecords() {
return receiveMessageRecords;
}
public ArrayList<CallRecord> getCallingLnCityRecords() {
return callingLnCityRecords;
}
}
class MobilePhoneLnCityRule extends ChargeRule
{
@Override
public double calCost (ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
CallRecord callRecord = callRecords.get(i);
/*根据打电话的区域划分*/
String callArea = callRecord.getCallingAddressAreaCode();
if(callArea.equals("0791"))
{
cost = cost + 0.1*time;
}
else if((callArea.compareTo("0790")>=0 && callArea.compareTo("0799")<=0)||(callArea.equals("0701")))
{
cost = cost + 0.3*time;
}
else
{
cost = cost + 0.6*time;
}
}
return cost;
}
}
class MobilePhoneLnlandRule extends ChargeRule
{
@Override
public double calCost (ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
CallRecord callRecord = callRecords.get(i);
/*根据打电话的区域划分*/
String callArea = callRecord.getCallingAddressAreaCode();
if(callArea.equals("0791"))
{
cost = cost + 0.3*time;
}
else if((callArea.compareTo("0790")>=0 && callArea.compareTo("0799")<=0)||(callArea.equals("0701")))
{
cost = cost + 0.3*time;
}
else
{
cost = cost + 0.6*time;
}
}
return cost;
}
}
class MobilePhoneLnProvinceRule extends ChargeRule
{
@Override
public double calCost (ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
CallRecord callRecord = callRecords.get(i);
/*根据打电话的区域划分*/
String callArea = callRecord.getCallingAddressAreaCode();
if(callArea.equals("0791"))
{
cost = cost + 0.2*time;
}
else if((callArea.compareTo("0790")>=0 && callArea.compareTo("0799")<=0)||(callArea.equals("0701")))
{
cost = cost + 0.3*time;
}
else
{
cost = cost + 0.6*time;
}
}
return cost;
}
}
class MobilePhoneCharging extends ChargeMode
{
private double monthlyRent = 15.0;
/*获取所有类型的通讯信息的花费*/
@Override
public double calCost(UserRecords userRecords) {
ArrayList<ChargeRule> chargeRules = this.getChargeRules();
MobilePhoneLnCityRule cityRule = (MobilePhoneLnCityRule)chargeRules.get(0);
MobilePhoneLnProvinceRule provinceRule = (MobilePhoneLnProvinceRule)chargeRules.get(1);
MobilePhoneLnlandRule lnlandRule = (MobilePhoneLnlandRule) chargeRules.get(2);
MobilePhoneAnswerLnProvinceRule phoneAnswerLnProvinceRule = (MobilePhoneAnswerLnProvinceRule) chargeRules.get(3);
MobilePhoneAnswerLnlandRule answerLnlandRule = (MobilePhoneAnswerLnlandRule) chargeRules.get(4);
double cost = 0;
cost = cost + cityRule.calCost(userRecords.getCallingLnCityRecords());
cost = cost + provinceRule.calCost(userRecords.getCallingLnProvinceRecords());
cost = cost + lnlandRule.calCost(userRecords.getCallingLnRecords());
cost = cost + phoneAnswerLnProvinceRule.calCost(userRecords.getAnswerLnProvinceRecords());
cost = cost + phoneAnswerLnProvinceRule.calCost(userRecords.getAnswerLnCityRecords());
cost = cost + answerLnlandRule.calCost(userRecords.getAnswerLnRecords());
return cost;
}
@Override
public double getMonthlyRent() {
return monthlyRent;
}
}
class MobilePhoneAnswerLnProvinceRule extends ChargeRule
{
@Override
public double calCost (ArrayList<CallRecord> callRecords) {
return 0;
}
}
class MobilePhoneAnswerLnlandRule extends ChargeRule {
@Override
public double calCost (ArrayList<CallRecord> callRecords) {
double cost = 0;
for(int i = 0;i<callRecords.size();i++)
{
int time = callRecords.get(i).getTime_minute();
cost = cost + 0.3*time;
}
return cost;
}
}
对期中考试的代码进行分析。
第一题
第一题是根据类图设计点线类,基本的类的设计结构是根据题目提供的类图来进行设计,其中方法的具体实现和main方法的实现是自己设计的。在设计过程中,为了降低点类和线类的耦合,在实现线类中的displat()方法时,我在点类中也写了display()方法,在线类的display()方法中使用点类的display()方法。降低类和类之间的耦合,可以在后期对代码优化和添加新需求时可以更方便的更改代码,提高代码的可扩展性。
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); double x1,y1,x2,y2; x1 = input.nextDouble(); y1 = input.nextDouble(); Point p1 = new Point(x1,y1); x2 = input.nextDouble(); y2 = input.nextDouble(); Point p2 = new Point(x2,y2); Line line = new Line(p1,p2,input.next()); if(x1>0&&x1<=200 && y1>0&&y1<=200 && x2>0&&x2<=200 && y2>0&&y2<=200) line.display(); else System.out.println("Wrong Format"); } } class Point { private double x,y; public Point() { x = 0.0; y = 0.0; } public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double X) { this.x = x; } public void setY(double y) { this.y = y; } public void display() { System.out.println(String.format("(%.2f,%.2f)",x,y )); } } class Line { private Point p1,p2; private String color; public Line() { p1 = new Point(); p2 = new Point(); } public Line(Point p1,Point p2,String color) { this.p1 = p1; this.p2 = p2; this.color = color; } public Point getterPoint1() { return p1; } public Point getterPoint2() { return p2; } public String getColor() { return color; } public void setterPoint1(Point p1) { this.p1 = p1; } public void setterpoint2(Point p2) { this.p2 = p2; } public void setColor(String color) { this.color = color; } public double getDistance() { return Math.sqrt(Math.pow((p1.getX()-p2.getX()),2)+Math.pow((p1.getY()-p2.getY()),2)); } public void display() { System.out.println("The line's color is:"+color); System.out.println("The line's begin point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p1.getX(),p1.getY()); System.out.println("The line's end point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p2.getX(),p2.getY()); System.out.format("The line's length is:%.2f",getDistance()); } }
第二题
第二题是根据题目提供的类图来设计点,线,面类,其中的点,线类可以使用第一题的代码。在第二题中主要考察继承和多态,点,线,面类都继承与Element类。我在面类中实现display()方法中使用了类成员中线类的display()方法。在第二题中还有对输入的值的大小限制,在main方法实现中先获取所有的用户输入再对用户的输入集中判断是否符合输入大小限制,如果符合输入规则则将数据传入类中,并调用相应的方法。
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); double x1,y1,x2,y2; x1 = input.nextDouble(); y1 = input.nextDouble(); Point p1 = new Point(x1,y1); x2 = input.nextDouble(); y2 = input.nextDouble(); Point p2 = new Point(x2,y2); Line line = new Line(p1,p2,input.next()); Plane plane = new Plane(line.getColor()); if(x1>0&&x1<=200 && y1>0&&y1<=200 && x2>0&&x2<=200 && y2>0&&y2<=200) { Element element = p1; element.display(); element = p2; element.display(); element = line; element.display(); element = plane; element.display(); } else System.out.println("Wrong Format"); } } class Point extends Element { private double x,y; public Point() { x = 0.0; y = 0.0; } public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double X) { this.x = x; } public void setY(double y) { this.y = y; } public void display() { System.out.println(String.format("(%.2f,%.2f)",x,y )); } } class Line extends Element { private Point p1,p2; private String color; public Line() { p1 = new Point(); p2 = new Point(); } public Line(Point p1,Point p2,String color) { this.p1 = p1; this.p2 = p2; this.color = color; } public Point getterPoint1() { return p1; } public Point getterPoint2() { return p2; } public String getColor() { return color; } public void setterPoint1(Point p1) { this.p1 = p1; } public void setterpoint2(Point p2) { this.p2 = p2; } public void setColor(String color) { this.color = color; } public double getDistance() { return Math.sqrt(Math.pow((p1.getX()-p2.getX()),2)+Math.pow((p1.getY()-p2.getY()),2)); } public void display() { System.out.println("The line's color is:"+color); System.out.println("The line's begin point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p1.getX(),p1.getY()); System.out.println("The line's end point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p2.getX(),p2.getY()); System.out.format("The line's length is:%.2f\n",getDistance()); } } class Element { public void display() { } } class Plane extends Element { private String color; public Plane() { color = "null"; } public Plane(String color) { this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void display() { System.out.println("The Plane's color is:"+color); } }
第三题
第三题是根据题目提供的类图在第二题的基础上设计一个容器类。在容器类的设计中我分别根据方法所需的功能调用ArrayList类中的相关功能, 在remove()方法中,对删除传入的信息进行了处理,使得删除的传入位置的减一,而不是在main()方法中对传入的数字减一,这样对该方法改正调整时可以只需要改变一处地方,这也是降低类之间耦合的一种方法。在main()方法的实现中使用了switch方法对选项进行相应的操作。
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); GeometryObject geometryObject = new GeometryObject(); int choice; choice = input.nextInt(); while(choice != 0) { switch(choice) { case 1: { geometryObject.add(new Point(input.nextDouble(),input.nextDouble())); } break; case 2: { Point p1 = new Point(input.nextDouble(),input.nextDouble()); Point p2 = new Point(input.nextDouble(),input.nextDouble()); geometryObject.add(new Line(p1,p2,input.next())); } break; case 3: { geometryObject.add(new Plane(input.next())); } break; case 4: { int index = input.nextInt(); geometryObject.remove(index-1); } break; } choice = input.nextInt(); } for(Element element:geometryObject.getList()) { element.display(); } } } class Point extends Element { private double x,y; public Point() { x = 0.0; y = 0.0; } public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double X) { this.x = x; } public void setY(double y) { this.y = y; } public void display() { System.out.println(String.format("(%.2f,%.2f)",x,y )); } } class Line extends Element { private Point p1,p2; private String color; public Line() { p1 = new Point(); p2 = new Point(); } public Line(Point p1,Point p2,String color) { this.p1 = p1; this.p2 = p2; this.color = color; } public Point getterPoint1() { return p1; } public Point getterPoint2() { return p2; } public String getColor() { return color; } public void setterPoint1(Point p1) { this.p1 = p1; } public void setterpoint2(Point p2) { this.p2 = p2; } public void setColor(String color) { this.color = color; } public double getDistance() { return Math.sqrt(Math.abs(Math.pow((p1.getX()-p2.getX()),2))+Math.abs(Math.pow((p1.getY()-p2.getY()),2))); } public void display() { System.out.println("The line's color is:"+color); System.out.println("The line's begin point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p1.getX(),p1.getY()); System.out.println("The line's end point's Coordinate is:"); System.out.format("(%.2f,%.2f)\n",p2.getX(),p2.getY()); System.out.format("The line's length is:%.2f\n",getDistance()); } } class Element { public void display() { } } class Plane extends Element { private String color; public Plane() { color = "null"; } public Plane(String color) { this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void display() { System.out.println("The Plane's color is:"+color); } } class GeometryObject { private ArrayList<Element> arrayList = new ArrayList<>(); public GeometryObject() { } public void add(Element element) { arrayList.add(element); } public void remove(int index) { if(index<arrayList.size()) arrayList.remove(index); } public ArrayList<Element> getList() { return arrayList; } }
对PTA题目集的代码进行分析
第一题
第一题考察的是正则表达式的使用。我设计了一个静态方法来识别字符是否是数字,在main()方法中根据正则表达式来处理传入的数据。
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); String str = input.nextLine(); while( !str.equals("end") ) { double sum = 0; char[] ta = str.toCharArray(); int n = str.length(); int begin = -1 , end = -1; for(int i=0 ; i<n ; i++) { if(begin == -1) { if( judgeNumber(ta[i]) ) { begin = i; end = i; } else continue; } if(begin != -1) { if( judgeNumber(ta[i]) == false || i==n-1) { //end = i; String number = str.substring(begin , end+1); sum = sum + Double.parseDouble(number); begin = -1; end = -1; } else { end = i; } } } System.out.printf("%.0f\n",sum); str = input.nextLine(); } } static boolean judgeNumber(char ta) { if(ta >= '0' && ta <= '9' ) return true; else return false; } }
第二题
第二题是点线系类的题目。在设计中是使用switch语句来处理各个选项,对每个选项的功能都分成各个方法,来更好的实现代码的复用。
import java.text.DecimalFormat; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String in = input.nextLine(); in = in.trim(); if(in.charAt(1)!=':') { System.out.println("Wrong Format"); } else { String str = in.substring(2); int size,count; MyPoint[] p; switch (in.charAt(0)) { case '1': size = 4; p = new MyPoint[size]; count = HeadInput.GetMyPoint(str,p,size); if(count==-1) { System.out.println("Wrong Format"); } else if(count!=size) { System.out.println("wrong number of points"); } else { MyPoint p1 = p[0],p2 = p[1] , p3 = p[2], p4 = p[3]; if(HeadInput.fourPointEqual(p1,p2,p3,p4)) { System.out.println("points coincide"); } else { if(!HeadInput.quadrilateral(p1,p2,p3,p4)) { System.out.println("false false"); } else { System.out.print("true "); MyQuadrilateral quadrilateral = new MyQuadrilateral(p1,p2,p3,p4); System.out.println(quadrilateral.styleParallel); } } } break; case '2': size = 4; p = new MyPoint[size]; count = HeadInput.GetMyPoint(str,p,size); if(count==-1) { System.out.println("Wrong Format"); } else if(count!=size) { System.out.println("wrong number of points"); } else { MyPoint p1 = p[0],p2 = p[1] , p3 = p[2], p4 = p[3]; if(HeadInput.fourPointEqual(p1,p2,p3,p4)) { System.out.println("not a quadrilateral"); } else { if(!HeadInput.quadrilateral(p1,p2,p3,p4)) { System.out.println("not a quadrilateral"); } else { MyQuadrilateral quadrilateral = new MyQuadrilateral(p1,p2,p3,p4); System.out.printf(quadrilateral.rhombus+" "+quadrilateral.rectangle+" "+quadrilateral.square); } } } break; case '3': size = 4; p = new MyPoint[size]; count = HeadInput.GetMyPoint(str,p,size); if(count==-1)//格式错误 { System.out.println("Wrong Format"); } else if(count!=size)//数量错误 { System.out.println("wrong number of points"); } else { MyPoint p1 = p[0],p2 = p[1] , p3 = p[2], p4 = p[3]; if(HeadInput.fourPointEqual(p1,p2,p3,p4)) { System.out.println("not a quadrilateral"); } else { if(!HeadInput.quadrilateral(p1,p2,p3,p4)) { System.out.println("not a quadrilateral"); } else { MyQuadrilateral quadrilateral = new MyQuadrilateral(p1,p2,p3,p4); System.out.println(quadrilateral.styleCave+" "+HeadInput.df3.format(quadrilateral.girth)+" "+HeadInput.df3.format(quadrilateral.area)); } } } break; case '4': size = 6; p = new MyPoint[size]; count = HeadInput.GetMyPoint(str,p,size); if(count==-1)//格式错误 { System.out.println("Wrong Format"); } else if(count!=size)//数量错误 { System.out.println("wrong number of points"); } else { MyPoint p1 = p[0],p2 = p[1] , p3 = p[2], p4 = p[3],p5 = p[4], p6 = p[5]; if(p1.equal(p2)) { System.out.println("points coincide"); } else { if(!HeadInput.quadrilateral(p3,p4,p5,p6)) { if(!HeadInput.judgeTriangle(p3,p4,p5,p6)) System.out.println("not a quadrilateral or triangle"); else { System.out.println("The line is coincide with one of the lines"); } } else { System.out.println("The line is coincide with one of the lines"); } } } break; case '5': size = 5; p = new MyPoint[size]; count = HeadInput.GetMyPoint(str,p,size); if(count==-1)//格式错误 { System.out.println("Wrong Format"); } else if(count!=size)//数量错误 { System.out.println("wrong number of points"); } else { MyPoint p1 = p[0],p2 = p[1] , p3 = p[2], p4 = p[3],p5 = p[4]; if(HeadInput.fourPointEqual(p2,p3,p4,p5)) { System.out.println("not a quadrilateral"); } else { if(!HeadInput.quadrilateral(p2,p3,p4,p5)) { if(!HeadInput.judgeTriangle(p2,p3,p4,p5)) System.out.println("not a quadrilateral or triangle"); else { System.out.println("The line is coincide with one of the lines"); } } else { System.out.println("The line is coincide with one of the lines"); } } } break; default: System.out.println("Wrong Format"); break; } } } } class HeadInput { static final DecimalFormat df3 = new DecimalFormat("0.0##");//保留3位小数,不足的不进位 static final DecimalFormat df6 = new DecimalFormat("0.0#####"); static int GetMyPoint(String in,MyPoint[] p , int size) { int current =0 ,prev = 0,count = 0,m=0; while(current!=-1) { current = in.indexOf(',',prev); String number1; if(current!=-1) number1 = in.substring(prev,current); else { return -1; } if(!HeadInput.formatDouble(number1)) { return -1; } prev = current +1; current = in.indexOf(' ',prev); String number2; if(current!=-1) number2 = in.substring(prev,current); else number2 = in.substring(prev); if(!HeadInput.formatDouble(number2)) { return -1; } prev = current +1; if(m<size) { p[m] = new MyPoint(number1,number2); m++; } count++; } return count; } static boolean formatDouble(String str) { boolean check1 = false,check2 = false,check = false; if(str.indexOf('.')!=-1) { String str1 = str.substring(0,str.indexOf('.')); String str2 = str.substring(str.indexOf('.')+1); for(int i=0;i<str1.length();i++) { char ch = str1.charAt(i); if(ch == '0') check1 = true; else if(ch=='1'||ch=='2'||ch=='3'||ch=='4'|| ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9') check1 = true; else { if((ch == '+'&& i==0)||(ch == '-'&& i==0)) ; else return false; } } for(int i=0;i<str2.length();i++) { char ch = str2.charAt(i); if(ch=='0'||ch=='1'||ch=='2'||ch=='3'||ch=='4'|| ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9') check2 = true; else { return false; } } return check1 && check2; } else { for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(i==0&&ch=='0'&&str.length()!=1) return false; else if(ch=='0'||ch=='1'||ch=='2'||ch=='3'||ch=='4'|| ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9') check = true; else { if((ch == '+'&& i==0)||(ch == '-'&& i==0)) ; else return false; } } return check; } } static boolean quadrilateral(MyPoint p1 , MyPoint p2 ,MyPoint p3 ,MyPoint p4) { Myline line = new Myline(p1,p2); if(line.inline(p3)||line.inline(p4)) return false; line = new Myline(p1,p3); if(line.inline(p2)||line.inline(p4)) return false; line = new Myline(p1,p4); if(line.inline(p2)||line.inline(p3)) return false; line = new Myline(p2,p3); if(line.inline(p1)||line.inline(p4)) return false; line = new Myline(p2,p4); if(line.inline(p1)||line.inline(p3)) return false; line = new Myline(p3,p4); if(line.inline(p1)||line.inline(p2)) return false; Myline tempLine = new Myline(p1,p2); if( (tempLine.pointSide(p3)&&tempLine.pointSide(p4)) || (!tempLine.pointSide(p3)&&!tempLine.pointSide(p4))) return true; else return false; } static boolean judgeTriangle(MyPoint p1 , MyPoint p2 ,MyPoint p3 ,MyPoint p4) { Myline line1; MyPoint X,Y,Z,S; if( !p1.equal(p2)) { if(p1.x<p2.x) { X = p1; Y = p2; } else { Y = p1; X = p2; } Z = p3; } else { if(p1.x<p3.x) { X = p1; Y = p3; } else { Y = p1; X = p3; } Z = p2; } S = p4; line1 = new Myline(X,Y); if( !line1.inline(p3) || line1.inline(p4)) return false; if(X.equal(Z)||Y.equal(Z)) return true; else//z在x和Y之间 { if(Z.x>X.x&&Z.x<Y.x) return true; else return false; } } static boolean fourPointEqual(MyPoint p1 , MyPoint p2 ,MyPoint p3 ,MyPoint p4) { return p1.equal(p2) || p1.equal(p3) || p1.equal(p4) || p2.equal(p3) || p2.equal(p4) || p3.equal(p4); } } class MyQuadrilateral { MyPoint pa,pb,pc,pd; Myline a,b,c,d; double area, girth; boolean styleCave; boolean rhombus; boolean rectangle; boolean styleParallel; boolean square; MyQuadrilateral(MyPoint p1 , MyPoint p2 ,MyPoint p3 ,MyPoint p4) { pa = p1; pb = p2; pc = p3; pd = p4; a = new Myline(pa,pb); b = new Myline(pb,pc); c = new Myline(pc,pd); d = new Myline(pd,pa); girth = a.length+b.length+c.length+d.length; if(a.parallel(c)&&b.parallel(d)) styleParallel = true; else styleParallel = false; if(a.length==b.length&&b.length==c.length&&c.length==d.length) rhombus = true; else rhombus = false; if(a.apeak(b)&&b.apeak(c)&&c.apeak(d)) rectangle = true; else rectangle = false; if(rhombus&&rectangle) square = true; else square = false; double s1 , s2; MyTriangle tr1 = new MyTriangle(pa,pb,pc); MyTriangle tr2 = new MyTriangle(pc,pd,pa); s1 = tr1.area+tr2.area; MyTriangle tr3 = new MyTriangle(pb,pc,pd); MyTriangle tr4 = new MyTriangle(pd,pa,pb); s2 = tr3.area + tr4.area; s1 = Double.parseDouble(HeadInput.df6.format(s1)); s2 = Double.parseDouble(HeadInput.df6.format(s2)); if(s1==s2) styleCave = true; else styleCave = false; if(styleCave) area = s1; else { if(s1>s2) { if(tr1.area>tr2.area) area = tr1.area - tr2.area; else area = tr2.area - tr1.area; } else { if(tr3.area>tr4.area) area = tr3.area - tr4.area ; else area =tr4.area - tr3.area; } } } } class MyTriangle { MyPoint pa, pb, pc,barycenter; Myline a,b,c; String styleLine,styleAngle; double girth,area; MyTriangle(MyPoint[] p) { pa = p[0]; pb = p[1]; pc = p[2]; a = new Myline(pc, pb); b = new Myline(pa, pc); c = new Myline(pb, pa); girth = a.length+b.length+c.length; area = (1.0/4.0) * ( Math.sqrt( ((a.length+b.length+c.length) * (a.length+b.length-c.length) * (a.length+c.length - b.length) * (b.length +c.length-a.length)) )); barycenter = new MyPoint( (pa.x+ pb.x+ pc.x)/3.0 , (pa.y+ pb.y+ pc.y)/3.0 ); double max=0,mid=0,min=0; if(a.length>=b.length&&a.length>=c.length) { max = a.length; mid = b.length; min = c.length; } else if(b.length>=a.length&&b.length>=c.length) { max = b.length; mid = a.length; min = c.length; } else if(c.length>=b.length&&c.length>=a.length) { max = c.length; mid = a.length; min = b.length; } double temp; temp=(double)(mid*mid+min*min-max*max)/(2.0*mid*min); double theta=Math.acos(temp); theta=(180.0*theta)/Math.PI; if(theta>90&&theta<180) styleAngle = "obtuseTriangle"; else if(theta>0&&theta<90) styleAngle = "acuteTriangle"; else if(theta==90) styleAngle = "rightangledTriangle"; if(a.length == b.length && b.length == c.length) styleLine = "regularTriangle"; else if(a.length == b.length || a.length == c.length || c.length == b.length) styleLine = "isoscelesTriangle"; else styleLine = "normalTriangle"; } public MyTriangle(MyPoint p1, MyPoint p2, MyPoint p3) { pa = p1; pb = p2; pc = p3; a = new Myline(pc, pb); b = new Myline(pa, pc); c = new Myline(pb, pa); girth = a.length+b.length+c.length; area = (1.0/4.0) * ( Math.sqrt( ((a.length+b.length+c.length) * (a.length+b.length-c.length) * (a.length+c.length - b.length) * (b.length +c.length-a.length)) )); barycenter = new MyPoint( (pa.x+ pb.x+ pc.x)/3.0 , (pa.y+ pb.y+ pc.y)/3.0 ); double max=0,mid=0,min=0; if(a.length>=b.length&&a.length>=c.length) { max = a.length; mid = b.length; min = c.length; } else if(b.length>=a.length&&b.length>=c.length) { max = b.length; mid = a.length; min = c.length; } else if(c.length>=b.length&&c.length>=a.length) { max = c.length; mid = a.length; min = b.length; } double temp; temp=(double)(mid*mid+min*min-max*max)/(2.0*mid*min); double theta=Math.acos(temp); theta=(180.0*theta)/Math.PI; if(theta>90&&theta<180) styleAngle = "obtuseTriangle"; else if(theta>0&&theta<90) styleAngle = "acuteTriangle"; else if(theta==90) styleAngle = "rightangledTriangle"; if(a.length == b.length && b.length == c.length) styleLine = "regularTriangle"; else if(a.length == b.length || a.length == c.length || c.length == b.length) styleLine = "isoscelesTriangle"; else styleLine = "normalTriangle"; } int nodeToLine(Myline line,MyPoint[] point) { int count = 0 ; if (line.equal(a) || line.equal(b)||line.equal(c)) return -1; else if(line.inline(pa)) { point[0] = pa; return 1; } else if(line.inline(pb)) { point[0] = pb; return 1; } else if(line.inline(pc)) { point[0] = pc; return 1; } else { if(line.parallel(a)) { point[0] = line.nodeToLine(b); point[1] = line.nodeToLine(c); return 2; } else if(line.parallel(b)) { point[0] = line.nodeToLine(a); point[1] = line.nodeToLine(c); return 2; } else if(line.parallel(c)) { point[0] = line.nodeToLine(a); point[0] = line.nodeToLine(b); return 2; } else { int m = 0 ; MyPoint p1 = line.nodeToLine(a); MyPoint p2 = line.nodeToLine(b); MyPoint p3 = line.nodeToLine(c); if(line.pointInLine(p1)) { point[m] = p1; m++; } if(line.pointInLine(p2)) { point[m] = p2; m++; } if(line.pointInLine(p3)) { point[m] = p3; m++; } return 2; } } } } class Myline { MyPoint p1 , p2;//构成一条线段的两个点 double length;//线段长度 double k;//线的斜率 boolean exiteK;//斜率是否存在 double A,B,C,b;//线一般式的参数 Myline(MyPoint p1, MyPoint p2) { this.p1 = p1; this.p2 = p2; //判断,计算 斜截式的参数 if(p1.x==p2.x) exiteK=false; else { exiteK=true; k=(p2.y-p1.y)/(p2.x-p1.x); b=p1.y-k*p1.x; } A = p1.y-p2.y; B = p2.x-p1.x; C = (p2.y-p1.y)*p1.x - (p2.x-p1.x)*p1.y; length = p1.distance(p2); } double distanceToPoint(MyPoint p) { return (Math.abs( (A*p.x+B*p.y+C) )) / (Math.sqrt( (A*A + B*B) )); } double getY(double x) { if(B==0) return 0 ; else if(A==0) return (-1.0*C) / B; else return (-1.0*C-A*x) / B; } boolean equal(Myline line) { return this.A == line.A && this.B == line.B && this.C == line.C; } boolean parallel(Myline line) { if(!this.exiteK && !line.exiteK) return true; else if(this.exiteK && line.exiteK) { return this.k == line.k; } else return true; } boolean apeak(Myline line) { if( (this.exiteK==false&&line.k==0)||(line.exiteK==false&&this.k==0)) return true; else if(this.exiteK && line.exiteK) { if(this.k*line.k==-1) return true; else return false; } else return false; } boolean inline(MyPoint p ) { if(this.A==0) { if(p.y==this.p1.y) return true; else return false; } else if(this.B==0) { if(p.x==this.p1.x) return true; else return false; } else { if(p.y==this.getY(p.x)) return true; else return false; } } MyPoint nodeToLine(Myline line) { double x=0,y=0; if(this.exiteK&&line.exiteK) { x = (this.B*line.C - line.B*this.C) / (this.A*line.B - line.A*this.B); y = (this.A*line.C - line.A*this.C) / (this.B*line.A - line.B*this.A); } else if(this.exiteK && !line.exiteK) { x = (-1.0*line.C) / line.A; y = this.getY(x); } else if(!this.exiteK && line.exiteK) { x = (-1.0*this.C) / this.A; y = line.getY(x); } MyPoint point = new MyPoint(x,y); return point; } boolean pointInLine(MyPoint point) { if(this.inline(point)) { double max , min ; if(this.p1.x>this.p2.x) { max = this.p1.x; min = this.p2.x; } else { max = this.p2.x; min = this.p1.x; } if(point.x>min && point.x <max) return true; else return false; } else return false; } boolean pointSide(MyPoint point) { if(this.exiteK==false) { if(point.x>this.p1.x) return false; else return true; } else if(this.k==0) { if(point.y>this.p1.y) return true; else return false; } else { if(point.y > this.getY(point.x)) return true; else return false; } } } class MyPoint { double x,y; MyPoint(double x,double y) { this.x = x; this.y = y; } MyPoint(String x1,String y1) { x = Double.valueOf(x1); y = Double.valueOf(y1); } double distance(MyPoint p) { return Math.sqrt(Math.pow((x-p.x),2)+Math.pow((y-p.y),2)); } boolean equal(MyPoint p) { return (this.x==p.x&&this.y==p.y); } static boolean allInLine(MyPoint[] p) { Myline line = new Myline(p[0],p[1]); for(int i = 2;i<p.length;i++) { if( !line.inline(p[i])); return false; } return true; } }
第三题
第三题是设计一个银行业务类。在设计中根据题目写出了各个方法,在写代码的过程中逐步实现各个方法。
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); BankBusinese.welcome(); BankBusinese account = new BankBusinese(input.next(),input.next()); account.deposit(input.next(),input.nextInt()); account.withdraw(input.next(),input.nextInt()); account.withdraw(input.next(),input.nextInt()); account.withdraw(input.next(),input.nextInt()); BankBusinese.welcomeNext(); } } class BankBusinese { public static String bankNane = "中国银行"; private String name , password; int balance; public static void welcome() { System.out.println(bankNane+"欢迎您的到来!"); } public static void welcomeNext() { System.out.println("请收好您的证件和物品,欢迎您下次光临!"); } BankBusinese(String name,String password) { this.name = name; this.password = password; this.balance = 0; } public void deposit(String password , int sum) { if(password.equals(this.password)) { balance = balance + sum; System.out.println("您的余额有"+balance+".0元。"); } else { System.out.println("您的密码错误!"); } } public void withdraw(String password , int sum) { if(password.equals(this.password)) { if(sum<=balance) { balance = balance - sum; System.out.println("请取走钞票,您的余额还有"+balance+".0元。"); } else { System.out.println("您的余额不足!"); } } else { System.out.println("您的密码错误!"); } } }
踩坑心得
对期中考试的踩坑心得
在第二题和第三题中我没有看到Element类是一个抽象类,在代码中没有使用对应的修饰符。导致虽然测试点全过了,却因为没有根据类图来设计以至于第二题和三题没有得分。
这提醒了我,以后要仔细的看题,对类图观察仔细,要清楚的知道每个类的属性,和类与类之间的关系。
对PTA题目集的踩坑心得
在第二题中,我对于输入格式的判断没有做成相应的方法,导致每个case语句中都存在着很多相同判断格式的代码,代码的复用没有很好的设计,以至于代码量超出了题目限制。
着提醒了我,要尽量将每个功能分成更细小的功能,进可能的降低代码的复用。
改进建议
对期中考试的代码改进建议
在期中考试的第二题和第三题中对Element类修改为抽象类,其中的方法该为抽象方法。这样在后续的设计中可以保证继承其的类都实现了该方法。
对PTA题目集的代码改进建议
在第二题中对格式判断的代码做成多个方法,降低代码的复用。
总结
在期中考试,PTA题目集,实验二中,我学习到了很多关于类的设计的经验,知道了什么时候该用抽象类,应该要尽量降低类之间的耦合和对正则表达式的理解。其中对于正则表达式强大的功能还需要进一步的学习及研究。
在PTA题目集的题目,我认为应该尽量降低直接对数学知识的大量考察,而是通过算法题的方式考察,这样可以更好的提供同学们的算法能力。
标签:return,String,ArrayList,blog,cost,new,public 来源: https://www.cnblogs.com/tao51/p/16389514.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。